我正在使用以下代码将行导出到单个文本文件:
Sub export_Test()
Dim firstRow As Integer, lastRow As Integer, fileName As String
Dim myRow As Integer, myStr As String
firstRow = 10
lastRow = 29
For myRow = firstRow To lastRow
fileName = "C:\mallet\test\" & Cells(myRow, 1) & ".txt"
Open fileName For Append As #1
myStr = Cells(myRow, 2).Value
Print #1, myStr
Close #1
Next
End Sub
问题是此代码适用于特定行数。我想将此代码用于不同的数据样本,因此excel文件中的行数会有所不同,可能会有数千个。我需要将lastRow变量设置为无限数,并在遇到空行时退出For循环。
答案 0 :(得分:4)
此代码将从第10行开始并一直运行,直到在第二列中找到空白单元格。请注意,我也稍微缩短了你的代码(尽管它仍然对文件进行相同的写入):
Sub export_Test()
Dim myRow As Long
myRow = 10
While Cells(myRow, 2).Value <> ""
Open "C:\mallet\test\" & Cells(myRow, 1) & ".txt" For Append As #1
Print #1, Cells(myRow, 2).Value
Close #1
myRow = myRow + 1
Wend
End Sub
答案 1 :(得分:0)
这是来自我的项目的代码,它完全符合您的要求 - 以空白值结束
Sub export_Test()
Dim firstRow As Integer, lastRow As Integer, fileName As String
Dim myRow As Integer, myStr As String
firstRow = 10
myRow = firstRow
' Seed initial value
Cells(myRow, 1).Select
' Keep going until a blank cell is found
While Trim(ActiveCell.Value) <> ""
fileName = "C:\mallet\test\" & ActiveCell.Value & ".txt"
Open fileName For Append As #1
myStr = Cells(myRow, 2).Value
Print #1, myStr
Close #1
' Get the next value
myRow = myRow + 1
Cells(myRow, NameCol).Select
Wend
End Sub