Momo
Momo

Reputation: 153

VBA: Exit For Loop when row is empty

I'm using the following code to export rows to individual text files:

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

The problem is that this code is for a specific number of rows. I want to use this code for different data samples, so the number of rows in the excel file will vary and could number in the thousands. I need the lastRow variable to be set to an infinite number and exit the For Loop when it hits an empty row.

Upvotes: 3

Views: 19417

Answers (2)

Peter Albert
Peter Albert

Reputation: 17515

This code will start in row 10 and run until it finds a blank cell in the second column. Note that I also shortened your code a bit (though it still does the same writing to a file):

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

Upvotes: 4

cardmagik
cardmagik

Reputation: 1698

This is code from a project of mine that does exactly what you want - end with a blank value

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

Upvotes: 0

Related Questions