Search code examples
csvvbscript

Deleting rows with empty columns in .csv with vbs


I currently have to code a script for my work that deletes the complete row if column D is empty in a .csv file with vbs.

I found a solution that might work thought I struggle a bit tbh.

enter   Const xlUp = -4162    ' Excel variables are not defined in vbscript
'Set objFile = objFSO.OpenTextFile("Testexport_neu.csv", ForReading) 'Datei Quelle
    Dim oBook : Set oBook = objFile
    Dim oSheet : Set oSheet = oBook.Sheets(1)
    Dim iLastRow, iRow

iLastRow = oSheet.Cells(oSheet.Rows.Count, 3).End(xlUp).Row
For iRow = iLastRow to 1 Step -1 'assumes a header row otherwise use 1 instead of 2
    If oSheet.Range("D" & iRow) = "" Then
        oSheet.Range("D" & iRow).EntireRow.Delete ' delete row if blank
End If
  • Code by User Dave

now to my problem, as I can't find any helpful documentation I have no clue on how to implement the .csv file the right way. ... or what the oXYZ methods do...

Thanks for any advice

As to why I haven't commented on the original post where Dave put this code on, as this post was made in 2018 I wasn't sure if I revive any answers there tbh


Solution

  • Does it have to be VBScript ?

    Is your data really CSV (text based), like this ? Post a small example, it would help greatly.

    COLA;COLB;COLC;COLD;COLE;COLF
    AAA;BBB;CCC;DDD;EEE;FFF
    A2;B2;C2;;E2;F2           <<<< left out
    A3;B3;C3;D3;E3;F3
    

    The job would be trivial to do with AWK: split the lines (just set separator) then check if column D is empty, if NOT then print the entire line.

    Effectively this will do what you ask for: filter out lines with empty column D. Not by deleting it, but by outputting everything else. I will edit this post later with an example. AWK is a free program available for pretty much every OS out there.

    Same can be done with other tools.

    Btw, you seem to handle a CSV file like an Excel document, accessing Excel features. Excel wants Windows to believe CSV is actually an Excel sheet, when it's just text. This can lead to several unwanted effects as Excel tries to be "clever" on your behalf.