首页 文章

从Excel到Word的VBA粘贴结束子

提问于
浏览
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,以及粘贴和粘贴,但它总是有相同的结果 .

有没有人对这里发生的事情有任何想法,或者如何阻止它在粘贴后总是结束 .

编辑:我测试了这个,它在Office 2010上工作 . 它在Office 2013上不起作用 .

2 回答

  • 0

    它对我来说很好

    但建议你尝试这些调整,看看是否有效( AppActivate 是多余的) .

    Sub StartIt()
    Call webtext("a1:a10")
    End Sub
    

    main

    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
    
  • 2

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

    此外,似乎任何单词更改都应该在 With wordDoc 部分内完成,因为在某些时候正确地命中代码可能有点奇怪(虽然从未弄清楚为什么第一次丢失消息框) .

    感谢@brettdj提供测试方面的帮助,并为了解我的错误而道歉 .

相关问题