【问题标题】:Passing variables between VBA code in Excel and Word在 Excel 和 Word 中的 VBA 代码之间传递变量
【发布时间】:2019-11-16 00:15:09
【问题描述】:

我有一个 Excel VBA 子程序,它调用一个处理某些文件的 Word VBA 子程序。我需要 Word 子程序向 Excel 子程序报告操作是否成功。

我的问题是 WResult 布尔变量应该将成功或失败结果从 Word 传递回 Excel(它被传递给 Word 宏 ByRef)没有这样做,它根本不会改变 Excel。

有解决办法吗?如果可能的话,我想避免基于使用剪贴板或将值写入磁盘上的文件的解决方案。

我的代码在 Excel 中看起来像这样:

Dim objW As Word.Application
Dim objWFile As Word.Document
Dim my_FileNamePath As String
Public WResult As Boolean

Sub Main()
    Set objW = CreateObject("Word.Application")
    Set objWFile = objW.Documents.Open("C:\WordMacro.docm")

    'Run Word macro
    objW.Run "Manip_Text", my_FileNamePath, WResult
    If WResult Then
        Macro_Continue
    Else
        Err_Handling
    End If
End Sub

...在 Word 中:


Public Sub Manip_Text(my_FileNamePath As String, ByRef WResult As Boolean)

On Error GoTo IfError

'Word macro code here

WResult = True   'Set result to True if there were no errors and exit sub back to Excel
Exit Sub

IfError:
MsgBox "There was an error with the Word file"
WResult = False   'Set result to False and exit back to Excel

End Sub

【问题讨论】:

  • 我认为你不能从 word 中返回任何东西到 excel... 我的解决方法是创建一个带有 word app 的 txt 文件并将其命名为成功或失败,因此 excel 可以查找文件并知道是哪一个。
  • 您可以使用数据库并对其进行读写。它并不像听起来那么复杂,而且非常可靠。

标签: excel vba ms-word


【解决方案1】:

将 Word 中的 Sub 更改为返回布尔值的函数。

Run 方法返回被调用宏返回的任何内容。

词功能:

Public Function ReturnMethod(ByVal stringText As String) As Boolean
    MsgBox stringText

    ReturnMethod = True
End Function

Word中调用函数的Excel方法:

Sub TestReturnMethod()

    Dim a As String: a = "Hello there!"

    Dim objW As Object
    Dim objWFile As Object

    Set objW = CreateObject("Word.Application")
    Set objWFile = objW.Documents.Open("E:\SomeFolder\Test.docm")

    Dim returnValue As Boolean
    returnValue = objW.Run("ReturnMethod", a)

    MsgBox returnValue
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    相关资源
    最近更新 更多