YASPLS
YASPLS

Reputation: 71

Run Time Error 5 - Invalid Procedure Call or Argument - While Saving Word Document

I've been trying to solve this error for a while, and nothing I've found online has seemed to help. Basically I'm running a script in excel VBA that opens a word document, and then opens the Save As dialog box so that I can save the file with the name / location of my choosing. It's at this point that I get the run time error 5.

I'm using the the Do Loop to try to get around the error, and it worked for a while. But for some reason the problem is back now and I have no idea why.

I've added a Do Loop that keeps the code from moving forward until the file has a name. This worked for a while but mysteriously stopped working after a few hours

Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Set wdApp = GetObject(, "Word.Application")

If Err.Number <> 0 Then 'Word isn't already running
    Set wdApp = CreateObject("Word.Application")
End If

On Error GoTo 0
Set wdDoc = wdApp.Documents.Open(OFile)

'Clear the variable that contains the file path/name
SveReportName = ""


'Save word document as a new file
Set SveReport = wdApp.ActiveDocument.Application.FileDialog(msoFileDialogSaveAs)
With SveReport
' 3 is for 97-2003 - include for 2010, remove for 2003
    .FilterIndex = 3
    .Show
    SveReportName = SveReport.SelectedItems.Item(1)
    'This Do statement is here so that VBA just keeps adding 1+1 until the user has had time to name the tech report file, it should stop Run Time Error 5 from appearing
    Do
        a = 1 + 1
    Loop Until IsNull(SveReportName) = False
    wdDoc.SaveAs SveReportName
End With

Any idea what else might be going on?

Thanks in advance!

Upvotes: 0

Views: 1418

Answers (1)

SamP
SamP

Reputation: 176

Have a read of the MS docs on the object you're using, and specifically its note about the execute method which should be used right after the show method for a Save As:

https://learn.microsoft.com/en-us/office/vba/api/office.filedialog.show

I think it reduces your 'save' code to something like this, though I haven't tried it:

'Save word document as a new file
Set SveReport = wdApp.ActiveDocument.Application.FileDialog(msoFileDialogSaveAs)
With SveReport
    .FilterIndex = 3
    if .Show = -1 then .Execute
End With

Upvotes: 1

Related Questions