excel表格数据通过VBA导出至WORD表格
新建文件夹.rar
(19.41 KB)
excel表格数据通过设计好的VBA一键导出至指定的WORD文档的表格,包括表格中的文字和数字,Word中事先已有表格,但是Word表格的行数和列数会根据Excel的行和列变化,请教各位大神该怎么写VBA代码
Sub ExportToWord() ' Excel range to export Dim rng As Range Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:D10") ' Word application and document Dim wdApp As Word.Application Dim wdDoc As Word.Document Set wdApp = New Word.Application Set wdDoc = wdApp.Documents.Open("C:\Path\To\Word\Document.docx") ' Word table to export to Dim wdTbl As Word.Table Set wdTbl = wdDoc.Tables(1) ' Get dimensions of Excel range Dim rowCount As Long Dim colCount As Long rowCount = rng.Rows.Count colCount = rng.Columns.Count ' Check if table needs to be resized If rowCount > wdTbl.Rows.Count Then wdTbl.Rows.Add rowCount - wdTbl.Rows.Count End If If colCount > wdTbl.Columns.Count Then wdTbl.Columns.Add colCount - wdTbl.Columns.Count End If ' Export data from Excel range to Word table Dim i As Long Dim j As Long For i = 1 To rowCount For j = 1 To colCount wdTbl.Cell(i, j).Range.Text = rng.Cells(i, j).Value Next j Next i ' Clean up objects Set wdTbl = Nothing Set wdDoc = Nothing wdApp.Quit Set wdApp = Nothing End Sub