我们在下面的Word.Application
子函数中声明了Pro1
个对象。当我们需要返回Word.Document
对象时,应保持打开状态。如何退出父SubRoutuine中的Word应用程序(test01
)
我需要在objWord
函数中声明的Pro1
对象在运行test01
过程结束后,在没有提示的情况下安静地退出。
我有两个程序
执行此操作:
Sub test01()
WrdPDF objDoc:=Pro1 strPath:=ThisWorkbook.path & "\" & "rep.pdf"
End Sub
|
Function Pro1 As Word.Document
'Declaration
Dim objWord As Word.Application
' Here we declare a Word Application in the function and need
' quit that in another procedure (The parent one which is test01).
Dim objDocTotal As Word.Document
Dim objDoc As Word.Document
'Initializing
Worksheets("Salary").OLEObjects("PayCheck").Activate
Set objWord = GetObject(, "Word.Application")
objWord.Visible = False
Set objDoc = objWord.ActiveDocument
Set objDocTotal = objWord.Documents.Add
...
Proc1 = objDocTotal
End Function
|
Sub WrdPDF(objDoc As Object, strPath As String, Optional Opn As Boolean) 'MS-Word PDF
objDoc.ExportAsFixedFormat _
outputfileName:=strPath _
, exportformat:=wdExportFormatPDF _
, openafterexport:=Opn _
, optimizefor:=wdExportOptimizeForPrint _
, Range:=wdExportAllDocument _
, Item:=wdExportDocumentContent _
, includedocprops:=False _
, keepirm:=True _
, createbookmarks:=wdExportCreateNoBookmarks _
, docstructuretags:=True _
, bitmapmissingfonts:=True _
, useiso19005_1:=False
End Sub
问候。
答案 0 :(得分:2)
您无法在该子例程中退出并保持文档处于打开状态。一旦该子例程结束,变量objWord就不再可用 - 您已经"孤立" Word的例子。
我看到两种可能性,就是副手,两者都涉及从Proc1
传递和获取对象,以便您可以访问应用程序对象:
1)您可以在test_01中声明Word.Application对象并将其传递给Proc1
Sub test01()
Dim objWord as Word.Application
WrdPDF objDoc:=Proc1(objWord), strPath:=ThisWorkbook.path & "\" & "rep.pdf"
objWord.Quit 0
End Sub
Function Proc1(ref objWord as Word.Application) As Word.Document
Dim objDocTotal As Word.Document
Dim objDoc As Word.Document
'And so on, as you currently have, without declaring objWord here
2)您可以通过Proc1:
返回的文档对象访问应用程序对象Sub test01()
Dim objDoc as Word.Document
Dim objWord as Word.Application
Dim strPath as String
strPath = ThisWorkbook.path & "\" & "rep.pdf"
Set objDoc = Proc1
WrdPDF objDoc, strPath
Set objWord = objDoc.Application
objWord.Quit 0 'do not prompt to save changes
End Sub
我可能倾向于使用(2),但是当我测试它们时都起作用。