用vba編程實現壹鍵插入。
第壹步:創建帶宏的excel表格。
第二步:將excel表格和word的對應關系建立壹張表格。也就是告訴程序需要將excel哪個表格插入到word的哪個位置。如圖:
第三步:編制插入的程序。代碼如下:
Sub 插入表格()
Dim SS As String Dim wdoc As New Word.Application Dim 當前路徑, 導出路徑文件名, i, j Dim Str1, Str2, Str3 Dim tarr(1 To 100, 1 To 3) Dim filepathname As String 當前路徑 = ThisWorkbook.Path最後行號 = Sheets("數字表格").Range("B30").End(xlUp).Row 判斷 = 0 '? 導出文件名 = "報告作品.doc" filepathname = 當前路徑 & "\" & Tfile If Dir(filepathname) = "" Then '文件不存在 FileCopy 當前路徑 & "\" & Sfile, 當前路徑 & "\" & Tfile End If Sheets("數字表格").Select For i = KShh To 最後行號 tarr(i - KShh + 1, 1) = Sheets("數字表格").Cells(i, 1) tarr(i - KShh + 1, 2) = Sheets("數字表格").Cells(i, 2) tarr(i - KShh + 1, 3) = Sheets("數字表格").Cells(i, 3) Next i j = i - KShh '記錄需替換文本個數 導出路徑文件名 = 當前路徑 & "\" & Tfile With wdoc '打開word文檔 .Documents.Open 導出路徑文件名 .Visible = True End With For i = 1 To j Str1 = tarr(i, 1) Str2 = tarr(i, 2) Str3 = tarr(i, 3) Range(Str3).Select Application.CutCopyMode = False Selection.Copy With wdoc .Selection.HomeKey Unit:=wdStory '光標置於文件首 If .Selection.Find.Execute(Str1) Then '查找到指定字符串 .Selection.Text = "" '替換字符串 .Selection.PasteExcelTable False, False, False? '粘貼為表格 .Selection.WholeStory .Selection.Font.Size = 12 With .Options .DefaultBorderLineStyle = wdLineStyleSingle .DefaultBorderLineWidth = wdLineWidth050pt .DefaultBorderColor = wdColorAutomatic End With .Selection.Tables(1).PreferredWidthType = 3 .Selection.Tables(1).PreferredWidth = .CentimetersToPoints(15) End If End With Next i With wdoc '存盤後關閉WORD文檔 wdoc.Documents.Save wdoc.Quit Set wdoc = Nothing End With Sheets("首頁").Select
End Sub
第四步:創建word模板。並將需要插入表格的位置做好標識。如圖:
第五步:創建壹鍵式按鈕,並將宏指定到該按鈕。如圖:
這樣就可以實現壹鍵式插入表格了。
今後根據需求只要修改第二步的內容就可以通用該工具了。