vba - 如何在运行时从文档正文中动态读取 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':需要对象”。
这让我认为在运行时获取字符串是不可能的。谁能解释为什么会这样?
解决方案
该文本的末尾可能有一个回车。
也许尝试Replace
消除它:
WScript = ActiveDocument.Shapes("Text Box 1").TextFrame.TextRange.Text
WScript = Replace(WScript, Chr(13), "")
同样对于Notepad
.
推荐阅读
- javascript - 从 div 的中心开始滚动
- html - 使用“Enter”按钮提交表单不起作用
- android - Android Studio 模拟器:进程以退出代码 -1073740791 (0xC0000409) 完成
- architecture - 使用单点登录获取用户数据的最佳方式
- javascript - 如何使用 Debounce Lodash React Native 加快搜索速度
- javascript - 如何获取存储在网站 Firebase 存储中的图像列表?
- java - javax.ws.rs.ProcessingException:找不到内容类型应用程序/x-www-form-urlencoded 类型的编写器:javax.ws.rs.core.Form$1
- android - 如何更改通知图标?
- javascript - Angular 5-如何向构造函数添加多个参数?
- javascript - 为角度控制器脚本创建单独的文件时出现“ReferenceError:未定义角度”