0

I'm fairly new to VBA programming, but still managed to make a small code which exports an Excel sheet to a CSV file. This must be as user friendly as possible, so I came up with this:

Sub export_first()

    Application.DisplayAlerts = False

    Dim wb As Workbook, InitFileName As String, fileSaveName As String

    InitFileName = ThisWorkbook.Path & "\Export nr1_" & Format(Date, "yyyymmdd")

    Sheets("MySheetNameToExport").Copy

    Set wb = ActiveWorkbook

    fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitFileName, _
    fileFilter:="Semicolon separated CSV (*.csv), *.csv")

    With wb
        If fileSaveName <> "False" Then

            .SaveAs fileSaveName, FileFormat:=xlCSV, Local:=True
            .Close
        Else
            .Close False
            Exit Sub
        End If
    End With

End Sub

This works just fine. It is added to a button, and when the button is pressed, the codes does all the job. Now the thing is, my coworkers came up with an idea, that we should use columns that checks some values for the users (lets call them C, D) but when they export the worksheet, these columns must be ignored and not exported. What I tried to do is to extend the Sheets line like:

Sheets("MySheetNameToExport").Range("A:B, E:G").Copy

But when I add this modified line to my macro and run the code, Excel crashes and exports the very first sheet which is just some welcome text and is totally unnecessary.

1 Answer 1

1

I suggest first hiding columns C and D and then copying visible cells only from your range.

Columns("C:D").EntireColumn.Hidden = True
Sheets("MySheetNameToExport").Range("A:G").SpecialCells(xlCellTypeVisible).Copy
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is indeed a great way to do it, and I really like the idea! However if I implement your code and run the script, this still happens: the "select to save somewhere" box comes up, I hit okay, then the VBA project closes itself, all of the sheets get closed and only the main grey Excel and VBA window stays in front of me... And yeah almost forget: the first information sheet gets exported. Like only the very first sheet.
Okay, an another expert from another forum pointed out what the problem was. The SaveAs method was the culprit. Set NewSheet = Sheets.Add Sheets("Work1").Range("X:Y").Copy Destination:=NewSheet.Range("A1") NewSheet.Move Set wb = ActiveWorkbook This did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.