excel中vba将excel中数字和图表输出到word中
参考:https://wenku.baidu.com/view/6c60420ecc175527072208af.html
比如将选区变为图片保存到桌面:
1 Sub 将选区转为图片存到桌面() 2 Dim ans As Byte, Pic As String, Paths As String 3 On Error Resume Next 4 Paths = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" '记录“桌面”文件夹的路径 5 star: 6 '选择导出图片的格式 7 ans = Application.InputBox("输入1:保存为BMP图片;" + Chr(10) + "输入2:保存为PNG图片;" + Chr(10) + "输入3:保存为JPG图片。", "图片格式", 1, , , , , 1) 8 If err <> 0 Then MsgBox "只能输入1到3", 64, "提示": err.Clear: GoTo star '如果有误(输入的值在0-255之外)则返回重新输入 9 If ans < 1 Or ans > 3 Then MsgBox "输入错误": GoTo star '如果不等于1、2、3则重新输入 10 Pic = Choose(ans, ".BMP", ".PNG", ".JPG") '在三种格式间选择 11 If TypeName(Selection) = "Range" Then '如果选择的对象是单元格 12 Dim rng As Range 13 Set rng = Selection '将选区赋与变量rng 14 rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture '将rng区域复制为图片 15 ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count + 1).Cells(1).Select '选择一个空单元格 16 With ActiveSheet.ChartObjects.Add(0, 0, rng.Width, rng.Height).Chart '生成图表 17 .Paste '将图片粘贴到图表中 18 .Export Paths & Replace(rng.Address(0, 0), ":", "-") & Pic '将图表导出为图片文件 19 .Parent.Delete '删除图表对象 20 End With 21 rng.Select '选择rng对象 22 End If 23 Shell "EXPLORER.EXE " & Left(Paths, Len(Paths) - 1), vbMaximizedFocus '打开桌面 24 End Sub
下面参考这个:
http://excel-macro.tutorialhorizon.com/vba-excel-create-and-save-the-word-document/
VBA-Excel: Create and Save the Word document
For creating and saving the Microsoft Word Document using Microsoft Excel, you need to follow the steps below:
- Create the object of Microsoft Word
- Create a document object and add documents to it
- Make the MS Word visible
- Create a Selection object with the help of WordObject.
- Use this Selection object to type the text into the WordDocument.
- Save the document
Create the object of Microsoft Word
Set objWord = CreateObject(“Word.Application”)
Create a document object and add documents to it
Set objDoc = objWord.Documents.Add
Make the MS Word Visible
objWord.Visible = True
Create a Selection object with the help of WordObject.
Set objSelection = objWord.Selection
Use this Selection object to type the text into the WordDocument.
objSelection.TypeText (“This is my text in Word Document using Excel”)
Save the Document
objDoc.SaveAs (“D:\MyFirstSave”)
Complete Code:
Function FnWriteToWordDoc() Dim objWord Dim objDoc Dim objSelection Set objWord = CreateObject("Word.Application") Set objDoc = objWord.Documents.Add objWord.Visible = True Set objSelection = objWord.Selection objSelection.TypeText ("Saving this file after this text") objDoc.SaveAs ("D:\MyFirstSave") End Function