[英]VBA Macro - Export table data from Excel file to Word and create a section for each worksheet
I use a macro in VBA for exporting data coming from Excel into Word. 我在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
All data and table layout are retrieved in Word. 在Word中检索所有数据和表布局。 The Procedure will copy usedRange of each Worksheet to Word and page break by each Worksheet. 该过程会将每个工作表的usedRange复制到Word,并按每个工作表分页。
I would like to update this script by putting the name of the worksheet just before the copy/paste data for each worksheet. 我想通过将工作表的名称放在每个工作表的复制/粘贴数据之前来更新此脚本。
Could you tell me how to do that? 你能告诉我怎么做吗?
After updated the code: 更新代码后:
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
I obtain the error Object doesn't support this property or method
on the line newobj.ActiveWindow.TypeText ws.Name
我newobj.ActiveWindow.TypeText ws.Name
错误消息: Object doesn't support this property or method
在行newobj.ActiveWindow.TypeText ws.Name
上Object doesn't support this property or method
Could you please help me? 请你帮助我好吗?
Try adding this to declarations: 尝试将其添加到声明中:
Dim sheetName as String
And this below the For Each statement 在For Each语句下面
sheetName = ws.Name
newobj.ActiveWindow.TypeText (sheetName)
In fact The line 事实上线
newobj.ActiveWindow.Selection.InsertBreak Type:=7
inserts a page break: 7 corresponds to wdPageBreak. 插入一个分页符:7对应于wdPageBreak。 I inserted a next page section break by changing 7 to 2 (corresponding to wdSectionBreakNextPage). 我通过将7更改为2来插入下一页分节符(对应于wdSectionBreakNextPage)。
Sections in Word don't have names. Word中的节没有名称。 I insert the name of the worksheet above the table: 我在表上方插入工作表的名称:
newobj.ActiveWindow.Selection.TypeText sheetName
newobj.ActiveWindow.Selection.Style = ActiveDocument.Styles(-2)
newobj.ActiveWindow.Selection.TypeParagraph
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.