經常有人問怎麼樣使用 VBA 實現将 Excel 工作表導出到 Word 文檔中,下面的程序給出了一個範例,其功能為将工作簿中的所有工作表中的内容導出到 Word 文檔:
要在工程中引用WORD,勾選自己對應版本就行
Excel的sheet1
Excel---sheet2
在Excel的模塊中寫入如下代碼:
代碼截圖
運行後生成Word如下:
生成的文檔
---------------------------------------------------代碼-----------------------------------------------------
Sub ExcelToWord()
Dim wd As Word.Application
Dim wdDoc As Word.Document
Dim wks As Worksheet
Application.ScreenUpdating = False
Set wd = New Word.Application
Set wdDoc = wd.Documents.Add
For Each wks In ActiveWorkbook.Worksheets
wks.UsedRange.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
Application.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
If Not wks.Name = Worksheets(Worksheets.Count).Name Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
Next wks
Set wks = Nothing
With wd.ActiveWindow
If .View.SplitSpecial = wdPaneNone Then
.ActivePane.View.Type = wdPrintView
Else
.View.Type = wdPrintView
End If
End With
Set wdDoc = Nothing
wd.Visible = True
Set wd = Nothing
Application.ScreenUpdating = True
End Sub
更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!