Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VBA:行为空时退出循环_Vba_Excel - Fatal编程技术网

VBA:行为空时退出循环

VBA:行为空时退出循环,vba,excel,Vba,Excel,我使用以下代码将行导出到单个文本文件: 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

我使用以下代码将行导出到单个文本文件:

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循环。

这是我的一个项目中的代码,它完全满足您的需要-以空白值结束

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
子导出_测试()
将第一行设置为整数,最后一行设置为整数,文件名设置为字符串
将myRow设置为整数,myStr设置为字符串
第一行=10
myRow=第一行
“种子初始值”
单元格(myRow,1)。选择
'继续,直到找到空白单元格
而修剪(ActiveCell.Value)”时
fileName=“C:\mallet\test\”&ActiveCell.Value&“.txt”
打开附加为#1的文件名
myStr=单元格(myRow,2).Value
打印#1,myStr
关闭#1
'获取下一个值
myRow=myRow+1
单元格(myRow,NameCol)。选择
温德
端接头

此代码将从第10行开始运行,直到在第二列中找到空白单元格为止。请注意,我还将您的代码缩短了一点(尽管它仍然对文件执行相同的写入操作):

子导出_测试()
让我的行变长
myRow=10
While单元格(myRow,2)。值“”
打开“C:\mallet\test\”和单元格(myRow,1)和“.txt”以附加为#1
打印#1,单元格(myRow,2)。值
关闭#1
myRow=myRow+1
温德
端接头

另外,由于您使用的是行,建议将它们声明为
Long
而不是
integers
:)@Sid。在32位操作系统上,您应该始终使用
Long
,除非有特殊需要使用16位数字(
Integer
),我对vba还是相当陌生的。我的For循环会进入这个代码吗?这是用新代码修改的代码。但是,我没有测试它,所以您可能需要对它进行一些调整-它将在稍后的主要答案中出现。您可能希望根据@SiddharthRout上面的评论调整此代码。完成。虽然如果你也这么做了我也不会介意…:-)
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