使用 Excel VBA 中的参数调用 Word VBA Sub
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9535959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a Word VBA Sub with arguments from Excel VBA
提问by Pixel Elephant
I have a very simple Word sub in a dotm template:
我在 dotm 模板中有一个非常简单的 Word sub:
Sub YHelloThar(msg As String)
MsgBox (msg)
End Sub
I then have an Excel sub:
然后我有一个Excel子:
Sub CallWordSub()
Dim wdApp As Word.Application
Dim newDoc As Word.Document
'Word template location
strFile = "C:\Some\Folder\MyWordDoc.dotm"
'Get or create Word application
Set wdApp = GetObject(, "Word.Application")
If wdApp Is Nothing Then
Set wdApp = CreateObject("Word.Application")
End If
'Create new Word doc from template
Set newDoc= wdApp.Documents.Add(strFile)
'Call the YHelloThar sub from the word doc
Call wdApp.Run(strFile & "!YHelloThar", "Hello")
End If
End Sub
The last line gives me "Run-time Error '438': Object does not support this property or method."
最后一行给了我“运行时错误‘438’:对象不支持此属性或方法。”
I'm not sure what I am doing wrong - everything I have looked up indicates this is the proper way to do call subs from different applications.
我不确定我做错了什么 - 我查找的所有内容都表明这是从不同应用程序调用 subs 的正确方法。
Furthermore, if I change the last line to be a parameter-less call it suddenly works correctly.
此外,如果我将最后一行更改为无参数调用,它会突然正常工作。
回答by Siddharth Rout
TRIED AND TESTED
久经考验
Call wdApp.Run("YHelloThar", "Hello")
Also you have an extra End If
at the end. A typo I guess?
最后你还有一个额外End If
的。我猜是错别字?
TIP: To avoid runtime errors, you will have to handle error just before calling
提示:为避免运行时错误,您必须在调用之前处理错误
Set wdApp = GetObject(, "Word.Application")
FOLLOWUP OF MY TIP
跟进我的提示
Here is an example. Also I have used Late Binding so that it will work with every Office Version.
这是一个例子。我还使用了后期绑定,以便它适用于每个 Office 版本。
Sub Sample()
Dim wdApp As Object, newDoc As Object
Dim strFile As String
strFile = "C:\Some\Folder\MyWordDoc.dotm"
'~~> Establish an Word application object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
wdApp.Visible = True
Set newDoc = wdApp.Documents.Add(strFile)
Call wdApp.Run("YHelloThar", "Hello")
'
'~~> Rest of the code
'
End Sub