[英]Export from Excel to a word Document and insert a header in word
我有以下代码:
Sub CreateRapport()
Dim wdApp As Object
Dim wd As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wd = wdApp.Documents.Add
wdApp.Visible = True
Sheets("Rapport").Activate
Set Rng = ThisWorkbook.ActiveSheet.Range("A1:E76")
Rng.Copy
With wd.Range
.Collapse Direction:=0 'Slutet av dokumentet
.InsertParagraphAfter 'Lägg till rad
.Collapse Direction:=0 'Slutet av dokumentet
.PasteSpecial False, False, True 'Pasta som Enhanced Metafile
End With
End Sub
它的作用是使用范围A1:E76中的数据创建Word文档
我想在包含文字和图片的Word文档中插入标题。 此标头中的名称在同一工作表的单元格A1中。
如果有人可以帮助我,我将非常感激。 谢谢。
如何将文本从单元格A1添加到文档中:
wdApp.Selection.TypeText ThisWorkbook.ActiveSheet.Range("A1").Text
如何将当前文本转换为标题:
'***** Word VBA constant wdStyleHeading1 = -2
wdApp.Selection.Style = -2
如何添加图片:
wdApp.Selection.InlineShapes.AddPicture Filename:="PATH_TO_IMAGE", LinkToFile:=False, SaveWithDocument:=True
如果将上面的代码放在一起并直接在wdApp.Visible = True
行之后添加,您将在标题的末尾得到一个图像,但是我无法从您的问题中确切知道您希望文档的外观。
编辑
显示当前标题的代码:
'***** Word VBA constant wdSeekCurrentPageHeader = 9
wdApp.ActiveWindow.ActivePane.View.SeekView = 9
显示普通视图:
'***** Word VBA constant wdSeekMainDocument = 0
wdApp.ActiveWindow.ActivePane.View.SeekView = 0
将所有内容放在一起,将其粘贴到wdApp.Visible = True
行之后,这一次无需设置样式:
wdApp.ActiveWindow.ActivePane.View.SeekView = 9
wdApp.Selection.TypeText ThisWorkbook.ActiveSheet.Range("A1").Text
wdApp.Selection.InlineShapes.AddPicture Filename:="PATH_TO_IMAGE", LinkToFile:=False, SaveWithDocument:=True
wdApp.ActiveWindow.ActivePane.View.SeekView = 0
编辑2
我对将嵌入式图像从Excel传输到Word的建议是使用复制和粘贴:
'***** copy image from cell B1 in Excel
ThisWorkbook.ActiveSheet.Range("B1").Copy
'***** past image at the current position in Word
wdApp.Selection.Paste
该代码需要放在wdApp.Selection.TypeText
命令附近,具体取决于您要在何处显示图像。
编辑3
添加页码字段的代码:
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="PAGE ", PreserveFormatting:=True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.