excelvbaexcel-2010

What code can I use to skip the blanks in my cell?


I am new at this but so I need help! I have created a spreadsheet that I intend to export as a .txt file for uploading to my payroll software. The code is working great but I can't figure out how to get it skip the blank rows. I am wanting it to look in column A and if the corresponding cell in column d is blank it needs to skip it and keep going with the loop. So far nothing is working...

This is my current code. I don't know what to add or even where. This is working for everything I need except skipping the blanks.

Dim thisWS As Worksheet
Set thisWS = Sheet1
Dim LastRow As Long
Dim workArea As Range
With thisWS
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    Set workArea = .Range(.Cells(2, 2), .Cells(LastRow, 7))
End With

Dim saveFileName As String
saveFileName = Application.GetSaveAsFilename("2024Testing", "text files (*.txt), *.txt")

Open saveFileName For Output As #1

Dim i As Integer
Dim j As Integer
Dim lineText As String

For i = 1 To workArea.Rows.Count
    For j = 1 To workArea.Columns.Count
        lineText = IIf(j = 1, "", lineText & ",") & workArea.Cells(i, j)   
    Next j
    lineText = Left$(lineText, Len(lineText) - 2)
    Print #1, lineText
        
Next i
Close #1

MsgBox "Bonus Import File Created"

End Sub

This is the output... The line with the zero is what I need to be skipped.

BRA29001,BONUS,3201,12132024
BUN29001,BONUS,0,12132024
BYN29001,BONUS,3201,12132024

Solution

  • Something like this maybe:

    Sub TestCsvOutput()
        Const FLD_SEP As String = ","
        
        Dim thisWS As Worksheet, LastRow As Long
        Dim workArea As Range, data As Variant
        Dim r As Long, c As Long, lineText As String, fld
        
        Set thisWS = Sheet1
        With thisWS
            LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
            Set workArea = .Range(.Cells(2, 2), .Cells(LastRow, 7))
        End With
        
        Dim saveFileName As String
        saveFileName = Application.GetSaveAsFilename("2024Testing", "text files (*.txt), *.txt")
        
        Open saveFileName For Output As #1
        
        data = workArea.Value           'get all data as a 2D array (faster)
        For r = 1 To UBound(data, 1)    'loop data rows
            If Len(data(r, 3)) > 0 Then 'any data in Col D on the sheet?
                lineText = ""           'reset line text
                For c = 1 To UBound(data, 2) 'loop columns
                    fld = data(r, c)         'get field value
                    'wrap field value in quotes if it contains the separator
                    If InStr(fld, FLD_SEP) > 0 Then fld = """" & fld & """"
                    lineText = lineText & IIf(c > 1, FLD_SEP, "") & fld
                Next c
                Print #1, lineText
            End If 'col D not blank
        Next r
        
        Close #1
        
        MsgBox "Bonus Import File Created"
    
    End Sub