第二次运行宏时,我收到运行时错误。
Dim wApp as Object
Dim wDoc as Object
Set wApp = CreateObject("word.Application")
Set wDoc = wApp.Documents.Add(Template:="Test.dotm", Visible:=True)
关于 Microsoft 支持:
Visual Basic 已建立对 Word 的引用,因为有一行代码调用了 Word 对象、方法或属性,而没有使用 Word 对象变量对其进行限定。在结束程序之前,Visual Basic 不会释放此引用。当代码运行多次时,这个错误的引用会干扰自动化代码。
我在代码中没有看到任何不合格的对象、方法或属性。
我认为 MS Word 可能已经在运行。因此,这里有我的库中的几个例程,用于检查 MS Word 是否已在运行,并连接到该进程。
Option Explicit
Public Function MSWordIsRunning() As Boolean
'--- quick check to see if an instance of MS Word is running
Dim msApp As Object
On Error Resume Next
Set msApp = GetObject(, "Word.Application")
If Err > 0 Then
'--- not running
MSWordIsRunning = False
Else
'--- running
MSWordIsRunning = True
End If
End Function
Public Function AttachToMSWordApplication() As Word.Application
'--- finds an existing and running instance of MS Word, or starts
' the application if one is not already running
Dim msApp As Word.Application
On Error Resume Next
Set msApp = GetObject(, "Word.Application")
If Err > 0 Then
'--- we have to start one
' an exception will be raised if the application is not installed
Set msApp = CreateObject("Word.Application")
End If
Set AttachToMSWordApplication = msApp
End Function