Friday, November 6, 2015

Excel VBA "ERROR 2015" returned from Application.GetSaveAsFilename

I was scratching my head over the following Excel Macro code:

Dim vFileName as Variant

...
On Error GoTo ErrorHandler    
vFileName = Application.GetSaveAsFilename(strTaskOrder & ".pdf", _
    "PDF Files (*.pdf), *.pdf", _
    "Select PDF Name for " & strTaskOrder)
On Error GoTo 0


What was interesting is no runtime error was generated, (so I could not use the OnError code; printing the contents of vFileName in the Immediate window was "Error 2015" and the typename(vFileName) was returning "Error", but it was not an "Err" object. But what would work, (thanks to StackOverflow answer to similar issue) I was able to catch whether this was happening:

If IsError(vFileName) Then
    MsgBox "error"
End If


Well the actual problem was that I was omitting a parameter; the FilterIndex (1) of the File Filter; the correct call was:

vFileName = Application.GetSaveAsFilename(strTaskOrder & ".pdf", _
    "PDF Files (*.pdf), *.pdf", _
    1,
    "Select PDF Name for " & strTaskOrder)


Lesson learned: Double-check your parameters!