通过VBA从Excel复制后,以Word格式格式化表格

时间:2019-02-03 20:05:39

标签: excel vba ms-word

我想将文本从Excel复制到Word文件,在两者之间(在第50行和第51行之间)添加分页符,并在Word文件中设置表格格式,将表格的宽度调整为Word文档的页面

我尝试了InsertBreak和SetWidth方法,但是由于某种原因会产生错误(语法或对象未定义)。

Sub Button1()    
Dim wd As Object    
Worksheets("1").Activate    
Range("C15:C73").Copy    
Set wd = CreateObject("word.application")    
wd.documents.Add    
wd.Visible = True    
wd.activedocument.Range.Pasteexceltable False, False, True    

Worksheets("2").Activate    

End Sub     

上面是我当前使用的代码,该代码可以正常工作,但在包含第50行之后没有分页符,表的格式也不正确,即列太宽。

有人可能会乐于帮助/指出正确的方向吗?

1 个答案:

答案 0 :(得分:0)

尝试以下代码并对其进行自定义以满足您的需求:

Sub Button1()  

    ' Define object variables
    Dim wordObject As Object
    Dim wordDocument As Object
    Dim wordTable As Object
    Dim rangeToCopy As Range

    ' Define other variables
    Dim sheetName As String
    Dim rangeAddress As String
    Dim rowToInsertBreak As Integer

    ' >>>>>Customize
    sheetName = "Sheet1" ' Sheet name in Excel
    rangeAddress = "C15:C73" ' Range in Excel to copy from
    rowToInsertBreak = 25 ' (index starts at 0 and first row is the header

    ' Initiate word object
    Set wordObject = CreateObject("Word.Application")

    ' Add a new document
    Set wordDocument = wordObject.Documents.Add

    ' Make the window visible
    wordObject.Visible = True

    ' Define the range to copy
    Set rangeToCopy = ThisWorkbook.Worksheets(sheetName).Range(rangeAddress)

    ' Copy the range
    rangeToCopy.Copy

    ' Paste it into word
    wordDocument.Paragraphs(1).Range.PasteExcelTable _
        LinkedToExcel:=False, _
        WordFormatting:=False, _
        RTF:=False

    ' Reference the table we just pasted
    Set wordTable = wordDocument.Tables(1)

    ' Autofit the table
    wordTable.AutoFitBehavior 2 ' wdAutoFitWindow: Check https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa211923(v%3Doffice.11)

    ' Insert the page break after row
    wordTable.Rows(rowToInsertBreak).Range.InsertBreak Type:=7 ' wdPageBreak

    ' Clear The Clipboard
    Application.CutCopyMode = False

End Sub

您需要检查以下链接:

如何正确地将Excel表复制并粘贴到word中:
https://www.thespreadsheetguru.com/blog/2014/5/22/copy-paste-an-excel-table-into-microsoft-word-with-vba
注意:通常最好使用word作为参考

如何处理Word表中的分页符:
https://shaunakelly.com/word/styles/page-breaks-in-tables.html