简体   繁体   English

使用Excel VBA中的参数调用Word VBA Sub

[英]Calling a Word VBA Sub with arguments from Excel VBA

I have a very simple Word sub in a dotm template: 我在dotm模板中有一个非常简单的Word子句:

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. 此外,如果我将最后一行更改为无参数调用,它会突然正常工作。

TRIED AND TESTED 经过试验和测试

Call wdApp.Run("YHelloThar", "Hello")

Also you have an extra End If at the end. 你还有一个额外的End If在最后。 A typo I guess? 我猜错了?

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. 我也使用了Late Binding,因此它适用于每个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM