簡體   English   中英

將Word文檔范圍設置為Excel范圍

[英]Set Word Document Range to Excel Range

我有一個較大的項目,該項目可以幫助您基於多個報告(在其他工作表上)在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之間。

編輯:更多信息。 ws的示例圖片

也許您可以在此代碼中找到更好的方法。 本示例采用工作表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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM