VBA:行为空时退出For循环

我正在使用下面的代码将行导出到单个文本文件:

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文件中的行数会有所不同,可能会有数千个。 我需要将lastRowvariables设置为无限数字,并在For循环遇到空行时退出。

这段代码将从第10行开始运行,直到在第二列中find空白单元格为止。 请注意,我也缩短了一下你的代码(虽然它仍然在写一个文件):

 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 

这是我的一个项目的代码,完全按照你的要求 – 以一个空值结束

 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