Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Exit For Loop when row is empty

Tags:

excel

vba

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.

like image 715
Momo Avatar asked May 07 '26 16:05

Momo


1 Answers

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
like image 162
Peter Albert Avatar answered May 09 '26 14:05

Peter Albert