首页 文章

将Excel单元格复制到打开/活动的Word文档

提问于
浏览
-1

我几天来一直在努力解决一个小问题,我似乎无法在网上找到它 .

我制作了一些VBA excel代码将单元格复制到一个新的word文档,但现在我希望将单元格粘贴到已打开的word文档上 .

你们中的任何人都知道答案吗?

这是代码:

Sub Cheese()

    Dim WordDocument As Word.Application
    \/\/\/\/\/\/\/
    Set WordDocument = Word.Application  <<< This creates a new word document every time I press start**
    /\/\/\/\/\/\/\
    WordDocument.Documents.Add
    WordDocument.Visible = True

    Sheets("PssDataFDS").Range("D1", (Cells(Rows.Count, 1).End(xlUp))).Copy

    WordDocument.Selection.Paste

    WordDocument.Selection.Tables(1).AutoFitBehavior wdAutoFitWindow
    WordDocument.Selection.Tables(1).Range.ParagraphFormat.SpaceAfter = 0

    Application.CutCopyMode = False
    Set WordDocument = Nothing

End Sub

评论的部分显示了我的问题 . 它每次都会生成一个新文件 . 但我只想要一次 . (因此,当文件已经处于活动状态时,它会显示错误或其他内容)

2 回答

  • 0

    据我所知:

    您有一个打开的Word文档,并且您希望将Excel中的一系列单元格粘贴到您在Word文档中所做的选择上 .

    Public Sub Test()
    
        Dim WrdDoc As Word.Document
    
        'Get a reference to the open Word document.
        Set WrdDoc = GetObject("Full Path To Word Document\Doc1.docx")
    
        'Copy some cells from Excel.
        ThisWorkbook.Worksheets("Sheet1").Range("A1:B2").Copy
    
        'Paste over the selection in Word.
        WrdDoc.ActiveWindow.Selection.PasteExcelTable _
            LinkedToExcel:=False, _
            WordFormatting:=False, _
            RTF:=False
    
    End Sub
    
  • 0

    感谢@Darren Bartrup-Cook,我发现了这个问题 .

    我监督的代码中有一部分 .

    WordDocument.Documents.Add
    

    这不应该在代码中,因为它创建了一个新文档(这正是我不想要的东西) .

    抱歉浪费时间 .

相关问题