从 Excel 到 Word 的 VBA 粘贴结束子
-
23-12-2019 - |
题
总体目标是在 Excel 中获取 RTF 格式的文本并将其转换为 HTML。到目前为止,我无法让 Excel 以合理的方式做出响应,因此尝试使用 Word。我能够在 Word 中毫无问题地进行转换,因此希望通过将单元格复制出 Excel、粘贴到 Word 中,然后运行代码将格式转换为我想要的方式来自动化该过程。
我遇到一个问题,当我从 Excel VBA 粘贴到 Word 时,粘贴成功,但随后跳转到 End Sub
.
Sub webtext(r As String)
Range(r).Copy
Dim wordApp As Word.Application
Dim wordDoc As Word.Document
Set wordApp = CreateObject("word.Application")
Set wordDoc = wordApp.Documents.Add
wordApp.Visible = True
wordApp.Activate
wordApp.Selection.PasteSpecial
'Any code here is missed out
z = MsgBox("tada") 'this will never trigger
x=5 'this will never set
With wordDoc
'Operations on the text pasted would happen here
'but vba never gets here.
End With
'Code jumps to here
End Sub
我尝试过使用wordDoc和wordApp,以及paste和pastespecial,但它总是有相同的结果。
有谁知道这里发生了什么或者如何阻止它在粘贴后总是结束。
编辑:我已经测试过了,它可以在 Office 2010 上运行。它不适用于 Office 2013。
解决方案 2
看来解决了。VBA 调试器无法理解在命中 WordApp 部分后发生了什么,因此代码 出现 跳到该部分的末尾。
此外,似乎任何单词更改都应该在 With wordDoc
部分,因为有时在中间正确地敲击代码可能有点奇怪(尽管从未弄清楚为什么第一次缺少消息框)。
感谢@brettdj 在测试方面提供的帮助,并对我在理解发生的情况时的错误表示歉意。
其他提示
它对我来说效果很好
但建议您尝试这些调整,看看这是否有效(AppActivate
是多余的)。
Sub StartIt()
Call webtext("a1:a10")
End Sub
主要的
Sub webtext(r As String)
Range(r).Copy
Dim wordApp As Word.Application
Dim wordDoc As Word.Document
Set wordApp = New Word.Application
Set wordDoc = wordApp.Documents.Add
wordApp.Visible = True
With wordDoc
.ActiveWindow.Selection.Paste
End With
End Sub
不隶属于 StackOverflow