如何将 URL 作为形状添加到 Word 文档?

问题描述 投票:0回答:1

我正在尝试使用 VBA 将通过 API (api.qrserver,com) 生成的二维码放入 Word 表中。由于某些原因,无法使用“DisplayBarcode”。

这是对 API 的调用:

sURL = "https://api.qrserver.com/v1/create-qr-code/?data=" & UTF8_URL_Encode(VBA.Replace(QR_Value, " ", "+")) & "&size=240x240"

看起来有效。我尝试了 GET 命令并检索了一个字符串,据我解释,该字符串包含 PNG 格式的 QR 代码。

当我尝试使用

将图片添加为形状时
Set objGrafik = ActiveDocument.Shapes.AddPicture(sURL, True)

呼叫失败并显示

运行时错误5152

据我所知,AddPicture 方法需要一个纯文件名,并且不允许使用以下任何字符:/|?*<>:"。

我还尝试将 GET 结果存储在对象变量中:

Set oQRCode = http.responseText

但我收到错误

需要对象

如何使 URL 分配起作用或将结果存储为图片?

vba ms-word shapes
1个回答
0
投票

我不确定您可以将某些内容插入到 Word 中的任何方法(例如

Shapes.AddPicture
InlineShapes.AddPicture
Range.InsertFile
等)是否可以让您从任何旧的 https 网址执行此操作,尽管它似乎适用于某些网址.

但是,碰巧您可以使用 INCLUDEPICTURE 字段来完成此操作。例如

{ INCLUDEPICTURE https://api.qrserver.com/v1/create-qr-code/?data=Test&size=100x100 }

这是一些用于执行此操作的示例 VBA

Sub insertqrcode()
Dim sUrl As String
Dim f As Word.Field
Dim r1 As Word.Range
Dim r2 As Word.Range

' This is just a test - plug your own Url in.
sUrl = "https://api.qrserver.com/v1/create-qr-code/?data=abcdef&size=100x100"
' Pick an empty test cell in a table
Set r1 = ActiveDocument.Tables(1).Cell(5, 4).Range
' We have to remove the end of cell character to add the field to the range
' Simplify
Set r2 = r1.Duplicate
r2.Collapse WdCollapseDirection.wdCollapseStart
Set f = r2.Fields.Add(r2, WdFieldType.wdFieldIncludePicture, sUrl, False)
' If you don't want the field code any more, do this
f.Unlink
' check that we have a new inline shape that we could work with more
' if necessary
Debug.Print r1.InlineShapes.count
Set f = Nothing
Set r2 = Nothing
Set r1 = Nothing
End Sub

使用 INCLUDEPICTURE 甚至可以在当前版本的 Mac Word 上使用(尽管我还没有在 Mac 上测试过特定的 VBA 部分)。

我见过的唯一其他方法是使用 WinHTTP 从 Web 服务获取结果,使用 ADODB 将其流式传输到本地磁盘文件,然后使用 AddPicture 或其他任何方法来包含该文件,因此更加复杂并且不会也可以在 Mac 上工作。

© www.soinside.com 2019 - 2024. All rights reserved.