将Word文档范围设置为Excel范围

时间:2018-04-10 15:55:14

标签: excel vba excel-vba

我有一个更大的项目,可以帮助基于多个报告(在其他工作表上)生成Excel中的字母,并将每个字母输入到一个常见的Word文档中,并在每个字母之间插入分页符。我试图解决一个错误被随机抛出的问题,说明剪贴板无效。以下代码偶尔会产生此错误:

容易出错的代码:

Sub ExportToWordDoc(ws As Worksheet, wordDoc As Word.Document, classCount As Long)
    Application.CutCopyMode = False
    ws.Range("A1:J" & classCount + 8).Copy
    DoEvents    'added in attempt to resolve random error
    Application.Wait (Now + TimeValue("0:00:01"))    'also added in attempt to resolve error
    wordDoc.Range(wordDoc.Content.End - 1).Paste    'line causes intermittent error
    wordDoc.Range(wordDoc.Content.End - 1).InsertBreak Type:=7
End Sub

我认为最终的解决方案是避免使用剪贴板迁移数据。有办法做到以下几点吗?目前,下面的代码会产生类型不匹配错误。

Sub ExportToWordDoc(ws As Worksheet, wordDoc As Word.Document, classCount As Long)
    wordDoc.Range(wordDoc.Content.End - 1).Text = ws.Range("A1:J" & classCount + 8).value
    wordDoc.Range(wordDoc.Content.End - 1).InsertBreak Type:=7
End Sub

非常感谢任何帮助。

仅供参考:生成的字母数可以在10到100之间。

编辑:更多信息。 Example image of ws

1 个答案:

答案 0 :(得分:1)

也许你可以在这段代码中找到更好的方法。此示例采用工作表1上的范围A1:A10,并将其导出到名为“表格报告”的现有Word文档中的第一个表。 注意:它不使用副本。

    Sub Export_Table_Data_Word()

        'Name of the existing Word document
        Const stWordDocument As String = "Table Report.docx"

        'Word objects.
        Dim wdApp As Word.Application
        Dim wdDoc As Word.Document
        Dim wdCell As Word.Cell

        'Excel objects
        Dim wbBook As Workbook
        Dim wsSheet As Worksheet

        'Count used in a FOR loop to fill the Word table.
        Dim lnCountItems As Long

        'Variant to hold the data to be exported.
        Dim vaData As Variant

        'Initialize the Excel objects
        Set wbBook = ThisWorkbook
        Set wsSheet = wbBook.Worksheets("Sheet1")
        vaData = wsSheet.Range("A1:A10").Value

        'Instantiate Word and open the "Table Reports" document.
        Set wdApp = New Word.Application
        Set wdDoc = wdApp.Documents.Open(wbBook.Path &; "\" &; stWordDocument)

        lnCountItems = 1

        'Place the data from the variant into the table in the Word doc.
        For Each wdCell In wdDoc.Tables(1).Columns(1).Cells
            wdCell.Range.Text = vaData(lnCountItems, 1)
            lnCountItems = lnCountItems + 1
        Next wdCell

        'Save and close the Word doc.
        With wdDoc
            .Save
            .Close
        End With

        wdApp.Quit

        'Null out the variables.
        Set wdCell = Nothing
        Set wdDoc = Nothing
        Set wdApp = Nothing

        MsgBox "The " &; stWordDocument &; "'s table has succcessfully " &; vbNewLine &; _
               "been updated!", vbInformation

    End Sub