使用VBA將Excel指定單元格數據、字符串或者圖表對象插入到Word模板指定書簽處


准備工作:

1、首先需要提供一個word模板,並且標記好您要插入書簽的位置,定義書簽的命名。如圖

 

 

2、模擬您要插入的Excel原始數據和圖表對象

 

插入代碼如下:

Private Sub CommandButton1_Click()
    
    Dim App, WrdDoc, Mypath As String
    
    On Error Resume Next
    '定義原始模板的儲存路徑,默認和excel在同一路徑
    Mypath = ThisWorkbook.Path & "\模板.doc"
    '用Set關鍵字創建Word應用成序對象!
    Set App = CreateObject("Word.Application")
    App.Visible = True
    '打開這個Word文件!
    Set WrdDoc = App.Documents.Open(Mypath)
    '以當前模板創建一個新的模板
    Set word = App.Documents.Add(Mypath)
    '將excel指定單元格的數據寫入之前已經編輯定位好的word書簽位置
    word.Bookmarks("書簽1").Range = Range("b2")
    word.Bookmarks("書簽2").Range = Range("b3")
    word.Bookmarks("書簽3").Range = Range("b4")
    word.Bookmarks("書簽4").Range = Range("b5")
    word.Bookmarks("書簽5").Range = Range("b6")
    
    ''插入當前工作表的2個圖表對象到指定位置,並顯示出來
    ''更改word 插入對象的環繞方式
    ''http://www.debugease.com/vb/2205943.html
    With App
        ThisWorkbook.Worksheets("底稿數據").ChartObjects(1).Activate
        ActiveChart.ChartArea.Copy
        .ActiveDocument.Bookmarks("收入情況圖").Range.Select
        .Selection.Paste
        .ActiveDocument.InlineShapes.Item(1).ConvertToShape
        .ActiveDocument.Shapes.Item(1).WrapFormat.Type = wdWrapTight
        
        ThisWorkbook.Worksheets("底稿數據").ChartObjects(2).Activate
        ActiveChart.ChartArea.Copy
        .ActiveDocument.Bookmarks("支出情況圖").Range.Select
        .Selection.Paste
        .ActiveDocument.InlineShapes.Item(1).ConvertToShape
        .ActiveDocument.Shapes.Item(1).WrapFormat.Type = wdWrapTight '更改環繞方式
    End With
    
    Paths = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" '記錄“桌面”文件夾的路徑
    word.SaveAs Filename:=Paths & "2019年X月XXXX食堂收支分析報告" & ".doc" '另存為word報告成品
    word.Close ' 關閉文件
    App.Quit
    Set App = Nothing
    MsgBox "2019年X月XXXX食堂收支分析報告", vbInformation, "報告已生成到桌面"
    Shell "EXPLORER.EXE " & Left(Paths, Len(Paths) - 1), vbMaximizedFocus '打開桌面
End Sub

 

附件下載地址:

https://files.cnblogs.com/files/ty1216jhy/%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E9%A3%9F%E5%A0%82%E6%8A%A5%E5%91%8A.rar

聯系QQ:609682901

 

2020年5月日志:

-----------------------------------------不久之后我將這個小工具做成了VSTO外接程序,小學生代碼如下-------------------------------------------------------------

做成excel 外接程序好處就是,代碼不容易被篡改,使用相對更穩定,就代碼升級沒有VBA方便

 主要有二段核心代碼:

一、生成主要書簽數據和生成餅狀圖

  1   public void 刷新主要數據()
  2         {
  3             try
  4             {
  5                 app = Globals.ThisAddIn.Application;
  6                 excel.Workbook wbk = app.Workbooks["食堂報告模板2019.xls"];
  7                 excel.Worksheet wst1 = wbk.Worksheets["本月數據"];
  8                 excel.Worksheet wst2 = wbk.Worksheets["上月數據"];
  9                 excel.Worksheet wst3 = wbk.Worksheets["生成數據"];
 10                 excel.Worksheet wst4 = wbk.Worksheets["對比數據"];
 11                 wst3.Range["b2:b6"].ClearContents();
 12                 //提取收入說明
 13                 int lr1 = wst1.Range["a3"].get_End(excel.XlDirection.xlDown).Row;
 14                 string str1 = string.Empty;
 15                 if (checkBox2.Checked == true)
 16                 {
 17                     for (int i = 6; i < lr1 + 1; i++)
 18                     {
 19                         if ((String)wst1.Range["b" + i].Text != "")
 20                         {
 21                             str1 = str1 + "," + "\n" + wst1.Range["a" + i].Text + ":" + wst1.Range["b" + i].Text + ""; ;
 22                         }
 23                     }
 24                 }
 25                 else
 26                 {
 27                     for (int i = 6; i < lr1 + 1; i++)
 28                     {
 29                         if ((String)wst1.Range["b" + i].Text != "")
 30                         {
 31                             str1 = str1 + "," + wst1.Range["a" + i].Text + ":" + wst1.Range["b" + i].Text + "";
 32                         }
 33                     }
 34                 }
 35                 int len1 = str1.Length;
 36                 string str1_1 = str1.Substring(2, len1 - 2) + "";
 37                 wst3.Range["b2"].Value2 = str1_1.Replace(" ", "");//替換字符串中產生的空格
 38 
 39                 //提取支出說明
 40                 int lr2 = wst1.Range["d2"].get_End(excel.XlDirection.xlDown).Row;
 41                 string str2 = string.Empty;
 42                 if (checkBox2.Checked == true)
 43                 {
 44                     for (int i = 4; i < lr2 + 1; i++)
 45                     {
 46                         if ((String)wst1.Range["e" + i].Text != "")
 47                         {
 48                             str2 = str2 + "," + "\n" + wst1.Range["d" + i].Text + ":" + wst1.Range["e" + i].Text + ""; ;
 49                         }
 50                     }
 51                 }
 52                 else
 53                 {
 54                     for (int i = 4; i < lr2 + 1; i++)
 55                     {
 56                         if ((String)wst1.Range["e" + i].Text != "")
 57                         {
 58                             str2 = str2 + "," + wst1.Range["d" + i].Text + ":" + wst1.Range["e" + i].Text + ""; ;
 59                         }
 60                     }
 61                 }
 62 
 63                 int len2 = str2.Length;
 64                 string str2_1 = str2.Substring(2, len2 - 2) + "";
 65                 wst3.Range["b3"].Value2 = str2_1.Replace(" ", "");
 66 
 67                 //MessageBox.Show(str1_1);
 68                 //提取結余數據
 69                 int a = wst1.Range["b100"].get_End(excel.XlDirection.xlUp).Row;
 70                 int b = wst2.Range["b100"].End[excel.XlDirection.xlUp].Row;
 71                 string str3 = "上月結余數:" + wst2.Range["b" + b].Value2 + "元;";
 72                 string str4 = "本月結余數:" + string.Format("{0:N2}", wst1.Range["b" + a].Value2) + "元;";
 73                 string str5 = "上年結余數:" + wst1.Range["c4"].Value2 + "元;";
 74                 string str6 = "上月累計結余數:" + wst2.Range["c" + b].Value2 + "元;";
 75                 string str7 = "本月累計結余數:" + wst1.Range["c" + a].Value2 + "";
 76                 string res = str3 + "\n" + str4 + "\n" + str5 + "\n" + str6 + "\n" + str7 + "";
 77                 wst3.Range["b4"].Value2 = res;
 78 
 79                 //收入分析
 80                 if (wst4.Range["d2"].Value < 0)
 81                 {
 82                     wst4.Range["f2"].Value2 = "本月收入下滑:" + string.Format("{0:N2}", -wst4.Range["d2"].Value2) +
 83                         "元,環比下滑" + string.Format("{0:P}", -wst4.Range["e2"].Value2) + "";
 84                 }
 85                 else
 86                 if (wst4.Range["d2"].Value > 0)
 87                 {
 88                     wst4.Range["f2"].Value2 = "本月收入上漲:" + string.Format("{0:N2}", wst4.Range["d2"].Value2) +
 89                         "元,環比上漲" + string.Format("{0:P}", wst4.Range["e2"].Value2) + "";
 90                 }
 91                 else
 92                 {
 93                     wst4.Range["f2"].Value2 = "本月收入與上月持平。";
 94                 }
 95                 string res1 = wst4.Range["f2"].Value2;
 96                 //MessageBox.Show(res1);
 97                 //支出分析
 98                 if (wst4.Range["d3"].Value < 0)
 99                 {
100                     wst4.Range["f3"].Value2 = "本月支出下滑:" + string.Format("{0:N2}", -wst4.Range["d3"].Value2) +
101                         "元,環比下滑" + string.Format("{0:P}", -wst4.Range["e3"].Value2) + "";
102                 }
103                 else
104                 if (wst4.Range["d3"].Value > 0)
105                 {
106                     wst4.Range["f3"].Value2 = "本月支出上漲:" + string.Format("{0:N2}", wst4.Range["d3"].Value2) +
107                         "元,環比上漲" + string.Format("{0:P}", wst4.Range["e3"].Value2) + "";
108                 }
109                 else
110                 {
111                     wst4.Range["f3"].Value2 = "本月支出與上月持平。";
112                 }
113                 string res2 = wst4.Range["f3"].Value2;
114                 //MessageBox.Show(res2);
115                 //結余分析
116                 if (wst4.Range["d4"].Value < 0)
117                 {
118                     wst4.Range["f4"].Value2 = "本月收支結余下滑:" + string.Format("{0:N2}", -wst4.Range["d4"].Value2) +
119                         "元,環比下滑" + string.Format("{0:P}", wst4.Range["e4"].Value2) + "";
120                 }
121                 else
122                 if (wst4.Range["d4"].Value > 0)
123                 {
124                     wst4.Range["f4"].Value2 = "本月收支結余上漲:" + string.Format("{0:N2}", wst4.Range["d4"].Value2) +
125                         "元,環比上漲" + string.Format("{0:P}", wst4.Range["e4"].Value2) + "";
126                 }
127                 else
128                 {
129                     wst4.Range["f4"].Value2 = "本月收支結余與上月持平。";
130                 }
131                 string res3 = wst4.Range["f4"].Value2;
132 
133                 string res_1 = res1 + "主要原因:******" + "\n" + res2 + "主要原因:******" + "\n" + res3 + "主要原因:******";
134                 //MessageBox.Show(res_1);
135                 wst3.Range["b5"].Value2 = res_1;
136 
137                 string res_2 = "【寫報告就像拜菩薩一樣,全靠誠心!所以為表心意,建議大家還是手動寫報告】";
138                 wst3.Range["b6"].Value2 = res_2;
139             }
140             catch (Exception ex)
141             {
142                 MessageBox.Show(ex.ToString());
143             }
144         }
  1   public void 生成餅狀圖()
  2         {
  3             try
  4             {
  5                 app = Globals.ThisAddIn.Application;
  6                 excel.Workbook wbk = app.Workbooks["食堂報告模板2019.xls"];
  7                 excel.Worksheet wst = wbk.Worksheets["本月數據"];
  8                 excel.Worksheet wst4 = wbk.Worksheets["對比數據"];
  9                 wst4.Range["j1:n100"].ClearContents();
 10 
 11                 //收入項目和金額
 12                 int lr = wst.Range["a3"].get_End(excel.XlDirection.xlDown).Row;
 13                 int i = 2;
 14                 foreach (excel.Range rng in wst.Range["a6:a" + lr])
 15                 {
 16                     string str = rng.Value2.ToString();
 17                     String str1 = (String)rng.Offset[0, 1].Text;
 18                     string stri = "[^\u4e00-\u9fa5]";
 19                     //if (str.Substring(2, 1) != "(" && str1 != "")//
 20                     //2020年5月新報表格式修改,收入項提取不包含帶括號的子項目
 21                     if (!str.Contains("") && str1 != "" &&!str.Contains("收入合計") && !str.Contains("收支結余"))
 22                     {
 23                         //MessageBox.Show(str);
 24                         string result = Regex.Replace(str, stri, "");
 25                         wst4.Cells[i, "j"] = result;
 26                         wst4.Cells[i, "k"] = (String)rng.Offset[0, 1].Text;
 27                         i += 1;
 28                     }
 29                 }
 30                 //支出項目和金額
 31                 int j = 2;
 32                 int lr1 = wst.Range["d4"].get_End(excel.XlDirection.xlDown).Row - 1;
 33                 foreach (excel.Range rng in wst.Range["d5:d" + lr1])
 34                 {
 35                     string str = rng.Value2.ToString();
 36                     String str1 = (String)rng.Offset[0, 1].Text;
 37                     string stri = "[^\u4e00-\u9fa5]";
 38                     //2020年5月新報表格式修改,收入項提取不包含帶括號的子項目
 39                     //強制添加不包含str != "1、水電支出" && str != "2、基本伙食支出",因為下面的維修費和其他支出又必須提取,我靠,做表的人真是隨心所欲
 40                     if (!str.Contains("") && str1 != "" && !str.Contains("水電支出") && !str.Contains("基本伙食支出") && !str.Contains("人員支出"))
 41                     {
 42                         //MessageBox.Show(str);
 43                         string result = Regex.Replace(str, stri, "");
 44                         wst4.Cells[j, "m"] = result;
 45                         wst4.Cells[j, "n"] = (String)rng.Offset[0, 1].Text;
 46                         j += 1;
 47                     }
 48                 }
 49                 if ((String)wst.Range["e" + lr1].Text != "")
 50                 {
 51                     int m = wst4.Range["m2"].get_End(excel.XlDirection.xlDown).Row + 1;
 52                     wst4.Range["m" + m].Value2 = wst.Range["d" + lr1].Value2;
 53                     wst4.Range["n" + m].Value2 = wst.Range["d" + lr1].Offset[0, 1].Value;
 54                 }
 55                 wst4.Range["j1"].Value2 = "收入項目";
 56                 wst4.Range["k1"].Value2 = "收入金額";
 57                 int r = wst4.Range["j2"].get_End(excel.XlDirection.xlDown).Row;
 58                 #region 此段同樣可以生成餅狀圖,只是同樣都是XlChartType.xl3DPie,為何形狀會不一樣
 59                 /*
 60                  */
 61                 //excel.ChartObjects chartObjects = (excel.ChartObjects)wst4.ChartObjects();
 62                 //excel.ChartObject chartObject = chartObjects.Add(wst4.Range["a8"].Left, wst4.Range["a8"].Top, 362, 200);
 63                 //excel.Chart chart = chartObject.Chart;
 64                 //chart.ChartType = excel.XlChartType.xl3DPie;
 65                 //chart.SetSourceData(wst4.Range["j1:k" + r]);
 66                 //chart.SetElement(MsoChartElementType.msoElementLegendRight);
 67                 //chart.Legend.Top = 8.5;
 68                 //chart.Legend.Height = 200;
 69                 //wst4.ChartObjects(1).Name = "收入xl3DPie";
 70                 /*
 71                  * 
 72                  */
 73                 #endregion
 74                 wst4.Activate();
 75                 wst4.Range["j1:k" + r].Select();
 76                 //office版本語法差異
 77                 if (Single.Parse(app.Version) >= 15)
 78                 {
 79                     wst4.Shapes.AddChart2(-1, XlChartType.xl3DPie, wst4.Range["a8"].Left, wst4.Range["a8"].Top, 380, 220, true);
 80                 }
 81                 else
 82                 {
 83                     wst4.Shapes.AddChart(XlChartType.xl3DPie, wst4.Range["a8"].Left, wst4.Range["a8"].Top, 380, 220);
 84                 }
 85                 wst4.ChartObjects(1).Name = "收入xl3DPie";
 86                 wst4.ChartObjects("收入xl3DPie").Chart.SetElement(MsoChartElementType.msoElementLegendRight);
 87                 wst4.ChartObjects("收入xl3DPie").Chart.Legend.Top = 6.5;
 88                 wst4.ChartObjects("收入xl3DPie").Chart.Legend.Height = 210;
 89                 //excel.Chart chart_s = wst4.ChartObjects("收入xl3DPie").Chart;
 90                 //string style = Interaction.InputBox("請輸入1-7之間(包含)的數字", "圖形樣式", "文本內容", -1, -1);
 91                 //chart_s.ApplyLayout(int.Parse(style),chart_s.ChartType);
 92                 //獲取圖像的標題,當更改成無標題的圖像是會報錯
 93                 //string sr = wst4.ChartObjects("收入xl3DPie").Chart.ChartTitle.Text;
 94                 //MessageBox.Show(sr);
 95 
 96                 wst4.Range["m1"].Value2 = "支出項目";
 97                 wst4.Range["n1"].Value2 = "支出金額";
 98                 int k = wst4.Range["m2"].get_End(excel.XlDirection.xlDown).Row;
 99 
100                 wst4.Range["m1:n" + k].Select();
101                 if (Single.Parse(app.Version) >= 15)
102                 {
103                     wst4.Shapes.AddChart2(-1, XlChartType.xl3DPie, wst4.Range["f8"].Left, wst4.Range["f8"].Top, 380, 220, true);
104                 }
105                 else
106                 {
107                     wst4.Shapes.AddChart(XlChartType.xl3DPie, wst4.Range["f8"].Left, wst4.Range["f8"].Top, 380, 220);
108                 }
109 
110                 wst4.ChartObjects(2).Name = "支出xl3DPie";
111                 wst4.ChartObjects("支出xl3DPie").Chart.SetElement(MsoChartElementType.msoElementLegendRight);
112                 wst4.ChartObjects("支出xl3DPie").Chart.Legend.Top = 6.5;
113                 wst4.ChartObjects("支出xl3DPie").Chart.Legend.Height = 210;
114                 string zc = wst4.ChartObjects("支出xl3DPie").Chart.ChartTitle.Text;
115                 app.ScreenUpdating = true;
116                 //MessageBox.Show(zc);
117             }
118             catch (Exception ex)
119             {
120                 MessageBox.Show(ex.ToString());
121             }
122 
123             finally
124             {
125                 //檢驗圖表名稱
126                 string res = "";
127                 excel.Worksheet wst = Globals.ThisAddIn.Application.Workbooks["食堂報告模板2019.xls"].Worksheets["對比數據"];
128                 foreach (excel.Shape shape in wst.Shapes)
129                 {
130                     if (shape.Type == MsoShapeType.msoChart)
131                     {
132                         res = shape.Name + ":" + shape.Chart.ChartTitle.Text + "\n" + res;
133                         //MessageBox.Show(shape.Chart.ChartTitle.Text);
134                     }
135                 }
136                 MessageBox.Show(res, "已生成圖表");
137             }
138         }

 二、導出報告

 1    private void Button3_Click(object sender, RibbonControlEventArgs e)
 2         {
 3             try
 4             {
 5                 app = Globals.ThisAddIn.Application;
 6                 app.StatusBar = "報告生成中,請勿關閉工作簿...";
 7                 System.Windows.Forms.Application.DoEvents();
 8                 //DataTable dt = LoadDataFromExcel("D:\\用戶目錄\\原始數據.xls");
 9                 //object oMissing = System.Reflection.Missing.Value;
10                 //創建一個Word應用程序實例
11                 word._Application oWord = new word.Application();
12                 //設置為不可見
13                 oWord.Visible = false;
14                 //模板文件地址,這里假設在X盤根目錄
15                 string localpath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
16                 string filename = localpath + "\\模板.doc";
17                 string year = DateTime.Now.Year.ToString();
18                 //object oTemplate = "D:\\用戶目錄\\模板.doc";
19                 //以模板為基礎生成文檔
20                 //Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
21                 //新版本VS已經取消了對參數的限制,可以不用謝missing
22                 word._Document oDoc = oWord.Documents.Add(filename);
23 
24                 //聲明書簽數組
25                 object[] oBookMark = new object[5];
26                 //賦值書簽名
27                 oBookMark[0] = "書簽1";
28                 oBookMark[1] = "書簽2";
29                 oBookMark[2] = "書簽3";
30                 oBookMark[3] = "書簽4";
31                 oBookMark[4] = "書簽5";
32                 //賦值任意數據到書簽的位置
33                 app = Globals.ThisAddIn.Application;
34                 excel.Workbook wbk = app.Workbooks["食堂報告模板2019.xls"];
35                 excel.Worksheet wst1 = wbk.Worksheets["本月數據"];
36                 excel.Worksheet wst2 = wbk.Worksheets["上月數據"];
37                 excel.Worksheet wst3 = wbk.Worksheets["生成數據"];
38                 excel.Worksheet wst4 = wbk.Worksheets["對比數據"];
39                 oDoc.Bookmarks["書簽1"].Range.Text = wst3.Range["b2"].Value2;
40                 oDoc.Bookmarks["書簽2"].Range.Text = wst3.Range["b3"].Value2;
41                 oDoc.Bookmarks["書簽3"].Range.Text = wst3.Range["b4"].Value2;
42                 oDoc.Bookmarks["書簽4"].Range.Text = wst3.Range["b5"].Value2;
43                 oDoc.Bookmarks["書簽5"].Range.Text = wst3.Range["b6"].Value2;
44                 //oDoc.Bookmarks.get_Item(ref oBookMark[0]).Range.Text = dt.Rows[0][1].ToString();
45                 //oDoc.Bookmarks.get_Item(ref oBookMark[1]).Range.Text = dt.Rows[1][1].ToString();
46                 //oDoc.Bookmarks.get_Item(ref oBookMark[2]).Range.Text = dt.Rows[2][1].ToString();
47                 //oDoc.Bookmarks.get_Item(ref oBookMark[3]).Range.Text = dt.Rows[3][1].ToString();
48                 //oDoc.Bookmarks.get_Item(ref oBookMark[4]).Range.Text = dt.Rows[4][1].ToString();
49                 /*對WOrd文檔的操作大全
50                  * https://www.cnblogs.com/xh6300/p/5915717.html
51                  */
52                 wst4.ChartObjects("收入xl3DPie").Activate();
53                 wst4.ChartObjects("收入xl3DPie").Chart.ChartArea.Copy();
54                 oWord.ActiveDocument.Bookmarks["收入情況圖"].Range.Select();
55                 oWord.Selection.Paste();
56                 word.Shape shape1 = oDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
57                 shape1.WrapFormat.Type = word.WdWrapType.wdWrapTight;
58 
59                 wst4.ChartObjects("支出xl3DPie").Activate();
60                 wst4.ChartObjects("支出xl3DPie").Chart.ChartArea.Copy();
61                 oWord.ActiveDocument.Bookmarks["支出情況圖"].Range.Select();
62                 oWord.Selection.Paste();
63                 word.Shape shape2 = oDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
64                 shape2.WrapFormat.Type = word.WdWrapType.wdWrapTight;
65 
66                 //彈出保存文件對話框,保存生成的Word
67                 SaveFileDialog sfd = new SaveFileDialog
68                 {
69                     Title = "請選擇保存您的新報告",
70                     Filter = "Word Document(*.doc)|*.doc",
71                     DefaultExt = "Word Document(*.doc)|*.doc",
72                     FileName = year + "年X月XXXX食堂收支分析報告"
73                 };
74                 if (sfd.ShowDialog() == DialogResult.OK)
75                 {
76                     object file_name = sfd.FileName;
77                     oDoc.SaveAs(file_name);
78                     oDoc.Close();
79                     //關閉word
80                     oWord.Quit();
81                     MessageBox.Show("報告已導出", "溫馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
82                     app.StatusBar = "報告已導出。";
83                 }
84                 else
85                 {
86                     MessageBox.Show("導出取消", "溫馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
87                     app.StatusBar = "報告未導出。";
88                 }
89             }
90             catch (Exception ex)
91             {
92                 MessageBox.Show(ex.ToString());
93             }
94         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM