为什么Word VBA告诉我对话框是打开的?

时间:2014-10-28 14:44:49

标签: vba word-vba word-2010

我正在尝试将选区复制到新文档然后将其导出为PDF,但我收到的错误是我无法解决的。

ActiveWindow.Close False行上我被告知

  

运行时错误'5479':
  您无法关闭Microsoft Word,因为对话框已打开。单击“确定”,切换到“单词”,然后关闭对话框。

除非导出到PDF操作正在启动对话框,否则我不知道将打开哪个对话框。

任何人都可以请一些亮点吗?感谢。

'** Copy the selection *'
Selection.Copy

'** Create a new document to paste the copied text into *'
Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0

'** Paste the copied text *'
Selection.PasteAndFormat (wdUseDestinationStylesRecovery)

'** Change the location of the file open directory *'
ChangeFileOpenDirectory OpenDirectory

'** Export the document to PDF *'
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
    OpenDirectory & "\ZENworks.pdf", ExportFormat:= _
    wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _
    wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
    Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
    CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
    BitmapMissingFonts:=True, UseISO19005_1:=False

'** Close the new document *'
ActiveWindow.Close False

CopyToNewDocument = True

2 个答案:

答案 0 :(得分:0)

应该是ActiveDocument.Close而不是ActiveWindow.Close

答案 1 :(得分:0)

特别是在处理多个文件时,使用对象变量来表示文件是最佳做法,这样您就可以更轻松地处理这些文件,并且不需要尝试记住哪个是活动在任何特定时间,您都可以直接引用该对象。

针对您的具体问题,请确保关闭文档,而不是 Window

Sub foo()
Dim OpenDirectory As String
Dim tempDoc As Document

'Modify as needed...
OpenDirectory = CreateObject("Wscript.Shell").SpecialFolders("Desktop")

Selection.Copy

'** Create a new document to paste the copied text into *'
Set tempDoc = Documents.Add(Template:="Normal", NewTemplate:=False, DocumentType:=0)

'** Paste the copied text *'
tempDoc.Range.PasteAndFormat (wdUseDestinationStylesRecovery)

'** Change the location of the file open directory *'
ChangeFileOpenDirectory OpenDirectory

'** Export the document to PDF *'
tempDoc.ExportAsFixedFormat OutputFileName:= _
    OpenDirectory & "\ZENworks.pdf", ExportFormat:= _
    wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _
    wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
    Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
    CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
    BitmapMissingFonts:=True, UseISO19005_1:=False

'** Close the new DOCUMENT *'
tempDoc.Close

CopyToNewDocument = True

End Sub

注意:通常建议您不要依赖ActivateSelect方法(这会详细解释)。当然,这不可能避免Word中的Selection,但更广泛的一点是,尽可能避免使用它会导致更好的代码在将来更容易阅读和维护。

相关问题