I have a table (Table8) that I need to export as .txt file. The code I'm currently using works fine but also exports empty rows from the table which messes up the .txt file for further use.
The table will have information in 1 to n rows (usually not more than 100). I would like to only export those rows, which have text in them (other rows have a formula in them and currently appear as blank in .txt file).
Code I'm currently using:
Sub saveToMtext()
Dim filename As String, lineText As String
Dim myrng As Range, i, j
filename = ThisWorkbook.path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"
ChDir (ThisWorkbook.path)
Open "m_text.txt" For Output As #1
FileFormat = xlText & CreateBackup = False
Set myrng = Range("Table8")
For i = 1 To myrng.Rows.Count
For j = 1 To myrng.Columns.Count
lineText = IIf(j = 1, "", lineText & vbTab) & myrng.Cells(i, j)
Next j
Print #1, lineText
Next i
Close #1
End Sub
I changed from regular IF to IF x Then Exit For and got it working.
Final code:
Sub saveToMtext()
Dim filename As String, lineText As String
Dim myrng As Range, i, j
Dim LValue As String
filename = ThisWorkbook.path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"
ChDir (ThisWorkbook.path)
Open "m_text.txt" For Output As #1
FileFormat = xlText & CreateBackup = False
Set myrng = Range("Table8")
k = 11
For i = 1 To myrng.Rows.Count
LValue = Cells(k, 121)
m = Len(LValue)
If m < 1 Then Exit For
For j = 1 To myrng.Columns.Count
lineText = IIf(j = 1, "", lineText & vbTab) & myrng.Cells(i, j)
Next j
Print #1, lineText
k = k + 1
Next i
Close #1
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.