Word用VBA一鍵導入Excel表格數(shù)據(jù)的方法

假如一個公司的員工信息被存儲在 Excel 中,需要將這些信息按照表格的形式呈現(xiàn)在公司的Word報告中,使用此代碼可以快速方便地實現(xiàn)這個任務(wù)。

案例:

Word用VBA提取Excel文件名為“員工資料”文件中的工作表名為sheet1的所有數(shù)據(jù),并在Word中以表格形式顯示。

如下面的圖片所示:

一、Word導入效果:

Word導入效果

二、EXCEL源表格:

EXCEL源表格

實現(xiàn)代碼:
Sub ExtractDataFromExcelAndCreateTableInWord()    ' 聲明變量    Dim ExcelFilePath As String    Dim ExcelApp As Object    Dim ExcelWorkbook As Object    Dim ExcelWorksheet As Object    Dim WordApp As Object    Dim WordDoc As Object    Dim WordTable As Object    Dim LastRow As Long    Dim LastColumn As Long    Dim i As Long    Dim j As Long        ' 設(shè)置 Excel 文件路徑    ExcelFilePath = "d:\員工資料.xlsx"        ' 創(chuàng)建 Excel 應(yīng)用程序?qū)ο蟛⒋蜷_工作簿    On Error Resume Next ' 開始錯誤處理程序    Set ExcelApp = CreateObject("Excel.Application")    Set ExcelWorkbook = ExcelApp.Workbooks.Open(ExcelFilePath)    On Error GoTo 0 ' 關(guān)閉錯誤處理程序        ' 檢查文件是否成功打開    If ExcelWorkbook Is Nothing Then        MsgBox "無法打開 Excel 文件,請檢查文件路徑是否正確或文件是否被其他程序或用戶占用。", vbCritical, "錯誤"        Exit Sub    End If        ' 獲取名為 "Sheet1" 的工作表    Set ExcelWorksheet = ExcelWorkbook.Worksheets("Sheet1")        ' 獲取數(shù)據(jù)行數(shù)和列數(shù)    LastRow = ExcelWorksheet.Cells(ExcelWorksheet.Rows.Count, 1).End(-4162).Row ' -4162 表示 xlUp    LastColumn = ExcelWorksheet.Cells(1, ExcelWorksheet.Columns.Count).End(-4159).Column ' -4159 表示 xlToLeft        ' 創(chuàng)建 Word 應(yīng)用程序?qū)ο蟛⑿陆ㄎ臋n    Set WordApp = CreateObject("Word.Application")    Set WordDoc = WordApp.Documents.Add()        ' 在 Word 文檔中創(chuàng)建表格    Set WordTable = WordDoc.Tables.Add(WordDoc.Range, LastRow, LastColumn)        ' 將 Excel 數(shù)據(jù)復制到 Word 表格中    For i = 1 To LastRow        For j = 1 To LastColumn            WordTable.Cell(i, j).Range.Text = ExcelWorksheet.Cells(i, j).Value        Next j    Next i        ' 設(shè)置表格樣式    With WordTable        ' 設(shè)置邊框樣式        .Borders.InsideLineStyle = wdLineStyleSingle        .Borders.OutsideLineStyle = wdLineStyleSingle                ' 設(shè)置表格自動調(diào)整寬度和列寬度自動調(diào)整        .AutoFitBehavior (wdAutoFitWindow)        .AllowAutoFit = True                ' 設(shè)置表格字體和大小        .Range.Font.Name = "宋體"        .Range.Font.Size = 10                ' 設(shè)置表頭樣式        .Rows(1).Shading.BackgroundPatternColor = wdColorGray15        .Rows(1).Range.Font.Bold = True        .Rows(1).Range.Font.Color = wdColorBlack                ' 設(shè)置表格內(nèi)容自動居中        .Range.ParagraphFormat.Alignment = wdAlignParagraphCenter    End With        ' 顯示 Word 應(yīng)用程序和文檔    WordApp.Visible = True    WordDoc.Activate        ' 關(guān)閉 Excel 應(yīng)用程序和工作簿    ExcelWorkbook.Close    ExcelApp.QuitEnd Sub

需要注意的是,在使用此代碼之前,需要確保已安裝了 Microsoft Excel 和 Microsoft Word,并且在代碼中指定的 Excel 文件路徑和工作表名稱是正確的。

標題:Word用VBA一鍵導入Excel表格數(shù)據(jù)的方法

地址:http://www.17168cn.cn/gzdm/11401.html