【问题标题】:How to Pass an Excel Variable from a Macro to a Word Macro in VBA如何将 Excel 变量从宏传递到 VBA 中的 Word 宏
【发布时间】:2014-11-19 22:56:02
【问题描述】:

我的目标是使用单元格引用来搜索单元格中的文本字符串,方法是打开某个 word 文档并将单元格或字符串传递到 word VBA 中的查找宏中。本质上,我试图将一个变量从一个 excel 宏传递到一个 word 宏中。我无法完成这项工作。我的目标是将变量Party 传递给名为ma​​cro5 的Word 宏。我可以通过不传入参数而仅在 word 宏中的文本中硬编码来使以下代码工作,但是当我尝试从 excel 传入参数时它不起作用。任何帮助将不胜感激。

我的excel宏代码:

Sub Open_Correct_WordDOC()

    ' Open_Correct_WordDOC Macro

    Dim WordApp As Object
    Dim WordDoc As Object

    Dim Party As String
    Party = "commercial"

    MsgBox Party

    Set WordApp = CreateObject("Word.Application")
    Set WordDoc = WordApp.Documents.Open(Filename:="J:enterdocumenthere.docx", _
        ReadOnly:=True)
    WordApp.Visible = True
    WordApp.Run "Normal.NewMacros.Macro5", Party

    Set WordDoc = Nothing
    Set WordApp = Nothing
End Sub

字宏代码:

Sub Macro5(xlvar As String)  
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = xlvar
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.Find.Execute
End Sub

【问题讨论】:

  • 为什么不直接在 Excel 中传输您的 word 宏?它会以同样的方式工作。您只需替换或声明您在 Word 宏中使用的 msWord 常量。
  • 有趣的问题。虽然@L42 的评论可能会提供一种解决方法,但它并不能解决根本问题。我可以验证问题是否存在(当 Word 宏在 Normal 模板中时),尽管 Application.Run 上的 Word VBA 帮助提示了发布的代码。

标签: vba excel parameter-passing


【解决方案1】:

在excel模块中:

Option Explicit

Public WordApp As Object
Public WordDoc As Object
Public Party As String

Sub Open_Correct_WordDOC()

    ' Open_Correct_WordDOC Macro

    Party = "commercial"

    MsgBox Party

    Set WordApp = CreateObject("Word.Application")
    Set WordDoc = WordApp.Documents.Open(Filename:="H:\docsearch.docx", ReadOnly:=True)
    WordApp.Visible = True
    WordApp.Activate
    WordApp.Run "Macro5", Party
    Set WordDoc = Nothing
    Set WordApp = Nothing
End Sub

我认为您的问题是您在 excel 宏中声明了对象和字符串 inside。我将它们公开,对我来说,代码运行良好。

插件:Word 宏位于 Normal 模板下的模块中。这对我来说很好。

【讨论】:

  • 解决了 OP 的问题。您已将 Word 宏从 Normal 模板移至文档。
  • 我的错,对不起。我已经更新了答案,并将 Word 宏放在 Normal 模板下的模块中。不过,它仍然对我有用。
猜你喜欢
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多