我将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
1条答案
按热度按时间fdbelqdn1#
您可以通过设置要处理的列来更改循环参数:
而不是
For col = 1 To rng.Columns.Count
由于for each循环中的变量必须是数组的Variant,因此将
col As Integer
声明更改为col As Variant