3

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

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

4

2 回答 2

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
于 2013-02-20T21:20:29.217 回答
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
于 2013-02-20T21:13:00.840 回答