后期绑定问题

时间:2018-01-24 12:18:05

标签: excel-vba ms-word vba excel

我从Excel启动了一个宏来控制Word文档。

为了防止引用问题(例如 Microsoft Word 15.0对象库 Microsoft Word 16.0对象库),我在主宏中使用后期绑定:

Public appWord as Object
Sub MainSub()
 Set appWord = GetObject(, "Word.Application")
 If appWord Is Nothing Then
     Set appWord = CreateObject("Word.Application")
 End If
 'Create temp file'
 '...'
 'Open temp file = strTempWordFile'
 Set docWord = appWord.Documents.Open(strTempWordFile)
 'Launch function to search text and remove it from the word document
 SearchAndRemove rgCell2.Text, docWord
End Sub

这是函数的摘录(在另一个模块中)

Sub SearchAndRemove(ByVal strSearchWord As String, ByRef docWord As Word.Document)
   Set selWordSelection = appWord.Selection 'That works
   selWordSelection.HomeKey Unit:=wdStory   'line with issue
   'do the search and remove'
End Sub

如果通过将docWord声明为Word.Document(需要引用 Microsoft Word 1X.0库)来调用Sub,则此行正常工作:

selWordSelection.HomeKey Unit:=wdStory

如果通过将docWord声明为Object( 需要引用 Microsoft Word 1X.0库)来调用Sub,则此行不起作用了。

1 个答案:

答案 0 :(得分:0)

如果您不知道等效数字,那么:

  • 打开相关应用程序(在您的情况下为Word
  • 打开VBE(Alt + F11)
  • 打开立即窗口(Ctrl + G)
  • 在紧邻窗口中输入关键字? (?wdStory
  • 使用它在代码中返回的数字。

在这种情况下,您需要将wdStory替换为6号 (并且只是阅读@AlexK注释的中间行 - 临时添加引用,并在即时窗口中显示?wdStory以查看它是什么
从未想过在当前应用中添加引用和使用即时窗口。我知道我会忘记再删除它。