首页 > 解决方案 > 如何在运行时从文档正文中动态读取 VBA 宏字符串?

问题描述

当我尝试将字符串移动到文档正文中并引用它们时,VBA 会出错。

我正在尝试做的一个例子。考虑以下宏:

Public Function Foo() As Variant
    Set Bar = CreateObject("WScript.Shell")
    Bar.Run ("C:\Windows\system32\notepad.exe")
End Function

我正在尝试将诸如“WScript.Shell”和“C:\Windows\system32\notepad.exe”之类的字符串移动到 Word 文档的正文中,例如在文本框中。

Public Function Foo()
    Dim WScript As String
    WScript = ActiveDocument.Shapes("Text Box 1").TextFrame.TextRange.Text
    Set Bar = CreateObject(WScript)
    Dim Notepad As String
    Notepad = ActiveDocument.Shapes("Text Box 2").TextFrame.TextRange.Text
    Bar.Run (Notepad)
End Function

文本框 1 和文本框 2 包含与以前完全相同的字符串,我可以使用 MsgBox() 读取它们,但现在宏在第 4 行的 CreateObject 调用失败,并出现错误:“运行时错误 '429': ActiveX组件无法创建对象”

如果我将字符串替换到宏中以让代码运行超过这一点并创建 WScript ActiveX 对象,则在调用 Bar.Run 方法时会出现错误:“运行时错误'424':需要对象”。

这让我认为在运行时获取字符串是不可能的。谁能解释为什么会这样?

标签: vbams-word

解决方案


该文本的末尾可能有一个回车。

也许尝试Replace消除它:

WScript = ActiveDocument.Shapes("Text Box 1").TextFrame.TextRange.Text
WScript = Replace(WScript, Chr(13), "")

同样对于Notepad.


推荐阅读