VBA宏 - 将表格数据从Excel文件导出到Word,并为每个工作表创建一个部分

时间:2017-12-06 13:14:21

标签: excel excel-vba ms-word worksheet vba

我在VBA中使用宏将Excel中的数据导出到Word中。

Sub ExportToWord()
    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add

    For Each ws In ActiveWorkbook.Sheets
        ws.UsedRange.Copy
        newobj.ActiveWindow.Selection.PasteExcelTable False, False, False
        newobj.ActiveWindow.Selection.InsertBreak Type:=7
    Next
        newobj.ActiveWindow.Selection.TypeBackspace
        newobj.ActiveWindow.Selection.TypeBackspace

    obj.Activate
    newobj.SaveAs Filename:=Application.ActiveWorkbook.Path & "\OLD\" & Split(ActiveWorkbook.Name, ".")(0)
End Sub

在Word中检索所有数据和表格布局。过程会将每个工作表的usedRange复制到每个工作表的Word和分页符。

我想通过在每个工作表的复制/粘贴数据之前放置工作表的名称来更新此脚本。

你能告诉我怎么做吗?

更新代码后:

Sub export_workbook_to_word()
    Dim sheetName As String
    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add

    For Each ws In ActiveWorkbook.Sheets
        sheetName = ws.Name
        ws.UsedRange.Copy
        newobj.ActiveWindow.TypeText ws.Name
        newobj.ActiveWindow.Selection.PasteExcelTable False, False, False
        newobj.ActiveWindow.Selection.InsertBreak Type:=7

    Next
        newobj.ActiveWindow.Selection.TypeBackspace
        newobj.ActiveWindow.Selection.TypeBackspace

    obj.Activate
    newobj.SaveAs Filename:=Application.ActiveWorkbook.Path & "\" & Split(ActiveWorkbook.Name, ".")(0)

End Sub

我在第Object doesn't support this property or method

上获得了错误newobj.ActiveWindow.TypeText ws.Name

你能帮我吗?

2 个答案:

答案 0 :(得分:0)

尝试将此添加到声明:

    Dim sheetName as String

这在For Each声明下面

    sheetName = ws.Name
    newobj.ActiveWindow.TypeText (sheetName)

答案 1 :(得分:0)

实际上该行

newobj.ActiveWindow.Selection.InsertBreak Type:=7

插入分页符:7对应于wdPageBreak。我通过将7更改为2(对应于wdSectionBreakNextPage)插入了下一页分节符。

Word中的部分没有名称。我在表格上方插入工作表的名称:

    newobj.ActiveWindow.Selection.TypeText sheetName
    newobj.ActiveWindow.Selection.Style = ActiveDocument.Styles(-2)
    newobj.ActiveWindow.Selection.TypeParagraph