Search code examples
excelvbaexport-to-csv

How to get Excel VBA code to save a filtered CSV as a new CSV?


I cannot get the Excel macro addin to take a filtered CSV imported into Excel and save it as a new CSV file. When it saves with a new name the file is blank. It does not contain the filtered data.

I've searched this site and others and I am using code based upon various code samples found here and elsewhere. I've included a MsgBox to review the path and filename before it is saved and it all looks fine. When I check and return the count of the number of workbooks, it simply shows a count of 1. So I don't believe it is seeing the Addin as a workbook.

If Right(Workbooks(1).path, 1) <> "\" Then
    path = Workbooks(1).path & "\Filtered_" & Workbooks(1).Name
Else
    path = Workbooks(1).path & "Filtered_" & Workbooks(1).Name
End If

MsgBox path

ThisWorkbook.SaveAs Filename:=path, FileFormat:=xlCSV

Application.DisplayAlerts = True

MsgBox "Filtering Complete", vbOKOnly, "Filtered CSV"

I'm expecting to open the file and see the filtered results. Instead, it is simply blank when I open the new file.


Solution

  • I needed to change "ThisWorkbook" to "Workbooks(1)":

    ThisWorkbook.SaveAs Filename:=path, FileFormat:=xlCSV
    

    ThisWorkbook refers to the "Addin" being used and not the actual workbook being edited.