将图像添加到Word文档并使用VBA进行缩放

时间:2010-01-08 18:21:35

标签: vba ms-word word-vba

如何使用VBA以编程方式将图像添加到word文档中。

我尝试在word文档中添加书签并尝试添加图片,但它总是添加到表单的顶部而不是书签区域。我应该坚持使用书签还是有其他方式来添加图像?

请参阅下面的代码:

Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")

Dim objWdRange As Word.Range
Dim GraphImage As String
Dim shortString As String 

shortString = Range("short").Value

GraphImage = "http://xxx.xxxxx.com/xxx/xxx.png?instrument=Image.png"

wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("C:\Program Files\My Dropbox\dailystrategy.doc")

Set objWdRange = wrdDoc.Content

With wrdDoc


    If wrdDoc.Bookmarks.Exists("shortString ") Then
        wrdDoc.Bookmarks("shortString ").Range.Text = shortString 
    End If      

     If wrdDoc.Bookmarks.Exists("GraphImage") Then
        wrdDoc.Bookmarks("GraphImage").Range.InlineShapes.AddPicture Filename:=GraphImage, LinkToFile:=False, SaveWithDocument:=True
     End If


    wrdDoc.SaveAs "c:\temp\test.doc"

  ' close the document
    Set wrdDoc = Nothing
    Set wrdApp = Nothing
End With

问候

1 个答案:

答案 0 :(得分:8)

好吧,首先我们需要稍微清理你的代码,如下所示。这在我的网站上运行良好 - 它将图像放在GraphicImage书签的正面,而不是文档的顶部 - 但是你的图像可能很大,它会延伸到顶部?

Dim objWdRange As Word.Range
Dim GraphImage As String
Dim shortString As String
shortString = Range("short").Value '? don't know what this is for
GraphImage = "http://xxx.xxxxx.com/xxx/xxx.png?instrument=Image.png"
wrdApp.Visible = True
    Set wrdDoc = wrdApp.Documents.Open("C:\Program Files\My Dropbox\dailystrategy.doc")
    Set objWdRange = wrdDoc.Content '? don't know what this is for
    With wrdDoc
        If .Bookmarks.Exists("shortString ") Then
           .Bookmarks("shortString ").Range.Text = shortString
        End If
     If .Bookmarks.Exists("GraphImage") Then
         Dim wrdPic As Word.InlineShape
         Set wrdPic = .Bookmarks("GraphImage").Range.InlineShapes.AddPicture(FileName:=GraphImage, LinkToFile:=False, SaveWithDocument:=True)
         wrdPic.ScaleHeight = 50
         wrdPic.ScaleWidth = 50
     End If
       .SaveAs "c:\temp\test.doc"
    End With
    wrdDoc.Close
    Set wrdDoc = Nothing
    wrdApp.Quit
    Set wrdApp = Nothing

编辑:2010年1月11日 上面的代码已更改为包含

 If .Bookmarks.Exists("GraphImage") Then
 Dim wrdPic As Word.InlineShape
 Set wrdPic = .Bookmarks("GraphImage").Range.InlineShapes.AddPicture(FileName:=GraphImage, LinkToFile:=False, SaveWithDocument:=True)
    wrdPic.ScaleHeight = 50
    wrdPic.ScaleWidth = 50
 End If

这会将图片设置为对象,然后使用缩放方法ScaleHeightScaleWidth使其在高度和宽度上都缩小50%。