【问题标题】:Adding image from URL in Word 2011 for Mac OSX using VBA使用 VBA 在 Word 2011 for Mac OSX 中从 URL 添加图像
【发布时间】:2016-01-31 01:50:51
【问题描述】:

我正在将project in Windows 移植到 OSX。我已经克服了 OSX Word 2011 not allowing you to send POSTs to a server 的 VBA 问题,并找到了 how to return a string result from an external script。现在我必须从使用我的外部脚本的返回构建的 URL 将图像插入到我的 Word 文件中。

目前的尝试如下,在 Windows 中可以工作,但在 OSX 中会导致 Word 崩溃:

Selection.InlineShapes.AddPicture FileName:=File_Name, _
    LinkToFile:=False, SaveWithDocument:=True

经过一些研究,看起来 MS 可能已将 OSX 中的此功能作为“安全风险”禁用。我仍然需要让它工作。有没有人知道 VBA for Office 2011 中的一种方法来完成这项工作,或者禁止这种解决方法?如果可能,我会尽量避免将图像文件写入磁盘。

更新:我已经创建了一个 Python 脚本,用于从 URL 获取图像文件,但我仍然不知道如何将这个图像从 Python 脚本获取到 VBA,然后从那里到光标所在位置的 Word 文档。脚本的重要部分如下。图像作为PIL 对象读入,我可以使用img.show() 显示它就好了,但我不确定这是什么文件类型或如何让VBA 接受它。

# Import the required libraries
from urllib2 import urlopen, URLError
from cStringIO import StringIO
from PIL import Image

# Send request to the server and receive response, with error handling!
try:
    # Read the response and print to a file
    result = StringIO(urlopen(args.webAddr + args.filename).read())
    img = Image.open(result)
    img.show()

except URLError, e:
    if hasattr(e, 'reason'):    # URL error case
        # a tuple containing error code and text error message
        print 'Error: Failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'):    # HTTP error case
        # HTTP error code, see section 10 of RFC 2616 for details
        print 'Error: The server could not fulfill the request.'
        print 'Error code: ', e.code

请注意,在上面,args.webAddrargs.filename 使用 argparse 库传递给脚本。该脚本有效,并将显示我期望的图像文件。关于如何将该图像导入 Word 2011 for OSX 并将其插入光标下的任何想法?

非常感谢!

编辑:在迁移到 github 后更新了项目的链接。

【问题讨论】:

  • 是的,Mac 上的 Vba 很恐怖。我自己被一些代码困住了。希望你得到的答案对你有用:)

标签: macos vba ms-word


【解决方案1】:

老问题,但没有答案,当图像位于 http URL 时,我在这里看到同样的崩溃。我认为您可以使用以下解决方法

Sub insertIncludePictureAndUnlink()
' Put your URL in here...
Const theImageURL As String = ""
Dim f As Word.Field
Dim r As Word.Range
Set f = Selection.Fields.Add(Range:=Selection.Range, Type:=wdFieldIncludePicture, Text:=Chr(34) & theImageURL & Chr(34), PreserveFormatting:=False)
Set r = f.Result
f.Unlink
Set f = Nothing
' should have an inlineshape in r
Debug.Print r.InlineShapes.Count
' so now you can do whatever you need, e.g....
r.Copy
Set r = Nothing
End Sub

【讨论】:

  • 我还没有对此进行测试,但如果你最终为我解决了我的问题,那么我会支持你给出的每一个答案!除了我认为他们过滤了投票轰炸,所以不是真的,但我会想要。
  • 成功了!我终于又开始搞砸了,你的解决方法解决了我的问题。还有更多工作要做,但这是一个巨大的帮助。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-08-19
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
相关资源
最近更新 更多