获取从Excel宏调用的Word宏函数的返回值



我正在执行Excel宏,以获取Word文件第一个表(基本上是表的标题(前面的第一段文本。

我的Excel宏如下:

Sub Main()
Set applicationWord = CreateObject("Word.Application")
Set documentWord = applicationWord.Documents.Open(Filename:="C:Users...my_word.docm", ReadOnly:=True)
applicationWord.Visible = True
applicationWord.Activate
applicationWord.Run "GetFirstString"
Set documentWord = Nothing
Set applicationWord = Nothing
End Sub

我们不能像任何其他编程语言那样编写str = applicationWord.Run "GetFirstString"来将返回的String保存在变量中。在我的Word文件my_word.docm中,我有以下宏GetFirstString:

Function GetFirstString() As String
GetFirstString = ActiveDocument.Tables(1).Range.Previous(Unit:=wdParagraph, Count:=1)

End Sub

这是一个原型。我想这样做,因为我想用从指定文件夹的每个Word文件中提取的文本编写一个Excel文件。我尝试了Excel中的以下宏,看看我是否能够使用Paragraph对象从Word文件中读取文本,但我遇到了一个错误,该代码无法与Excel VBA一起使用,VBA无法识别方法成员。

Private Sub ExtractionPrototype()
Dim applicationWord As Object
Dim documentWord As Object
Set applicationWord = GetObject(, "Word.Application")
applicationWord.Visible = True
Set documentWord = applicationWord.Documents.Open(cheminDossierReparation)

MsgBox documentWord.Tables(1).Range.Previous(Unit:=wdParagraph, Count:=1)
documentWord.Close savechanges:=False
End Sub

有什么方法可以将Word宏中的值返回到Excel宏中吗?文档中写道:;Run方法返回任何被调用的宏返回的"但是这个值到底是什么?如何得到它?

ExtractionPrototype例程不起作用的唯一原因是您使用了常数值wdParagraph,它是WdUnits枚举的一部分,但在Excel中没有定义。用它的值4替换它,或者在例程中将它声明为具有该值的常量。

"我们不能写CCD_;

正确,因为您错过了告诉VBA您需要返回值的方括号。所以你写str = applicationWord.Run("GetFirstString")

最新更新