Search code examples
excelvbaexport-to-csvsavefiledialog

VBA script to export sheets as CSV files to a specific location after deleting rows that are blank or "blank" but contain formula


I am working on a VBA script to allow manipulation and export of a number of worksheets as csv files from an Excel workbook. I'd like to be able to export a list of specified sheets as csv files to a save location that is able to be selected, in addition any cell in a specific column that is blank but may contain a formula needs to be have the entire row deleted. The below script is what I currently have and it seems to work to a point but there are three main issues:

  1. The line below will remove lines if the cell in column A is really blank i.e contains no formula, but does not work if formula is present: Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

  2. The cycling through the sheets is untidy but functional, is there a way to use a list of named sheets to make the script more concise?

  3. Ideally the save location would also be selectable from a choose file directory dialog box. Any suggestions on how to achieve this?

Many thanks in advance.

Sub createCSVfiles()
Application.ScreenUpdating = False
Application.DisplayAlerts = False

'Declare and set variables
Dim wb1 As Workbook, ws1 As Worksheet
Dim wbname As String, i As Integer
Set wb1 = ThisWorkbook

'Cycle through sheets
For i = 1 To Worksheets.Count
    wbname = Worksheets(i).Name

'Create Sheet1.csv
  If InStr(1, (Worksheets(i).Name), "Sheet1", vbTextCompare) > 0 Then
       Worksheets(i).Copy
       Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
       ActiveWorkbook.SaveAs Filename:="C:\Users\forename.surname\Desktop\export\" & ActiveSheet.Name & ".csv", _
       FileFormat:=xlCSV, CreateBackup:=False
       ActiveWorkbook.Close
      wb1.Activate
End If

'Create Sheet2.csv
If InStr(1, (Worksheets(i).Name), "Sheet2", vbTextCompare) > 0 Then
    Worksheets(i).Copy
    ActiveWorkbook.SaveAs Filename:="C:\Users\forename.surname\Desktop\export\" & ActiveSheet.Name & ".csv", _
    FileFormat:=xlCSV, CreateBackup:=False
    ActiveWorkbook.Close
    wb.Activate
End If

Next i

'Clean
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Solution

  • I think something like this is what you're looking for:

    Sub createCSVfiles()
    
        'Declare and set variables
        Dim wb As Workbook
        Dim ws As Worksheet
        Dim wsTemp As Worksheet
        Dim aSheets() As Variant
        Dim vSheet As Variant
        Dim sFilePath As String
        Dim sNewFileName As String
        Dim oShell As Object
        Dim i As Long
    
        'Select folder to save CSV files to
        Set oShell = CreateObject("Shell.Application")
        On Error Resume Next
        sFilePath = oShell.BrowseForFolder(0, "Select folder to save csv files", 0).Self.Path & Application.PathSeparator
        On Error GoTo 0
        If Len(sFilePath) = 0 Then Exit Sub 'Pressed cancel
    
        'Define sheet names here
        aSheets = Array("Sheet1", "Sheet2")
    
        With Application
            .Calculation = xlCalculationManual
            .EnableEvents = False
            .ScreenUpdating = False
            .DisplayAlerts = False
        End With
    
        Set wb = ThisWorkbook
    
        'Cycle through sheets
        For Each vSheet In aSheets
            'Test if sheet exists
            Set ws = Nothing
            On Error Resume Next
            Set ws = wb.Sheets(vSheet)
            On Error GoTo 0
            If Not ws Is Nothing Then
                'Sheet exists
                ws.Copy
                Set wsTemp = ActiveSheet
    
                'Remove rows with blanks in column A
                With wsTemp.Range("A1", wsTemp.Cells(wsTemp.Rows.Count, "A").End(xlUp))
                    .AutoFilter 1, "=", xlFilterValues
                    .Offset(1).EntireRow.Delete
                    .AutoFilter
                End With
    
                'Save and close
                wsTemp.Parent.SaveAs sFilePath & wsTemp.Name & ".csv", xlCSV
                wsTemp.Parent.Close False
            End If
        Next vSheet
    
        'Clean
        With Application
            .Calculation = xlCalculationAutomatic
            .EnableEvents = True
            .ScreenUpdating = True
            .DisplayAlerts = True
        End With
    
    End Sub