vba - 将图像添加到Word文档并使用VBA缩放

标签 vba ms-word

我如何以编程方式使用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

问候

最佳答案

好吧,首先,我们需要整理一下您的代码,如下所示。这在我的网站上运行良好-将图像放置在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%。

关于vba - 将图像添加到Word文档并使用VBA缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2029724/

相关文章:

vba - 一年中的月份自动递减

Excel VBA根据表中的单元格值显示/隐藏工作表

vba - 在 PowerPoint 中重命名对象

java - 使用 JTextPane 样式选项创建 Word 文件

vba - 重复 Microsoft Word VBA 直到找不到搜索结果

java - 如何使 Jackrabbit WebDAV servlet 允许使用 Microsoft Word 进行编辑?

excel - 在列中搜索 1 并在找到时将整行粘贴到另一个工作表中?

json - 从 MS Access 解析 VBA 中的 JSON (US BLS),更新

excel - 从 Word 中复制并粘贴为图片命名的 Excel 范围

java - 什么 API 可以使用 Java 将复选框添加到 MS Word 文件?