1

总体目标是在 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。

4

2 回答 2

2

对我来说效果很好

但建议您尝试这些调整,看看这是否有效(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
于 2014-02-27T11:24:46.373 回答
0

似乎解决了。VBA 调试器在到达 WordApp 部分后无法理解发生了什么,因此代码似乎跳到了该部分的末尾。

此外,似乎任何单词更改都应该在该With wordDoc部分中完成,因为有时在两者之间正确地敲代码可能有点奇怪(尽管从未弄清楚为什么第一次缺少消息框)。

感谢@brettdj 在测试方面的帮助,并为我在理解发生的事情时的错误道歉。

于 2014-03-03T11:18:14.273 回答