运行时错误5-无效的过程调用或参数-保存Word文档时

时间:2019-07-15 23:50:44

标签: excel vba ms-word

一段时间以来,我一直在尝试解决此错误,但我在网上发现的任何内容似乎都无济于事。基本上,我在excel VBA中运行一个脚本,该脚本会打开Word文档,然后打开“另存为”对话框,以便可以使用选择的名称/位置保存文件。正是在这一点上,我得到了运行时错误5。

我正在使用Do Loop来解决该错误,并且工作了一段时间。但是由于某种原因,问题又回来了,我也不知道为什么。

我添加了一个Do Loop,以防止代码向前移动直到文件具有名称。这工作了一段时间,但神秘地在几个小时后停止工作

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

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

已阅读有关所使用对象的MS文档,尤其是有关execute方法的注释,应在show方法之后立即将其用于另存为:

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

我认为它可以将您的“保存”代码简化为这样,尽管我没有尝试过:

'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