excel 将特定列的数据从范围导出到文本文件

unftdfkk  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(216)

我将Excel数据导出到文本文件。当我导出所有范围数据(例如"B2:E" & p)时,它可以工作。
在某些情况下,我只需要B & E列数据。

Sub make_textfile()

'Variable declarations
Dim myFileName As String, rng As Range, cellVal As Variant, row As Integer, col As Integer
Dim inputNumber As Long
inputNumber = InputBox("Please enter number : " & vbCrLf & vbCrLf & "It may be 30 or 50 or your custom number! ", "Insert Data")
'Full path of the text file
myFileName = "C:\Users\Desktop\Text_1.txt"
'Data range need to write on text file
p = inputNumber + 1
Set rng = ActiveSheet.Range("B2:E" & p)
'Open text file
Open myFileName For Output As #1
'Number of Rows
For row = 1 To rng.Rows.Count
    'Number of Columns
    For col = 1 To rng.Columns.Count
   
    cellVal = rng.Cells(row, col).Value
    'write cellVal on text file
    If col = rng.Columns.Count Then
        Print #1, cellVal & vbNewLine & vbNewLine
    Else
        Print #1, cellVal & vbNewLine & vbNewLine
    End If
    Next col
Next row
Close #1
End Sub
fdbelqdn

fdbelqdn1#

您可以通过设置要处理的列来更改循环参数:

For Each col In Array(1, rng.Columns.Count)

而不是For col = 1 To rng.Columns.Count
由于for each循环中的变量必须是数组的Variant,因此将col As Integer声明更改为col As Variant

相关问题