【问题标题】:Inserting a web image to an Excel cell将 Web 图像插入 Excel 单元格
【发布时间】:2015-10-19 21:32:15
【问题描述】:

我是 Excel VBA 的新手,因此我非常感谢任何帮助。我在网上找到了以下代码,可以将图像放入电子表格。原样的代码可以获取图像并将该图像放在活动表上,但我需要将该图像放在单元格中。那可能吗?下面是我目前拥有的宏。

所以 A 列将是 getImage2 将使用的值,而 B 列理想情况下应该有各自的图像。

Public Function getImage2(ByVal name As String) As String

  Dim imgURL As String

  Dim XMLhttp: Set XMLhttp = CreateObject("MSXML2.ServerXMLHTTP")

  XMLhttp.setTimeouts 1000, 1000, 1000, 1000

  imgURL = "http://cactus.nci.nih.gov/chemical/structure/" + name + "/image"


  XMLhttp.Open "GET", imgURL, False

  XMLhttp.send

  If XMLhttp.Status = 200 Then

   'It exists so get the image

    ActiveSheet.Shapes.AddPicture imgURL, msoFalse, msoTrue, 100, 100, 250, 250

  Else

    '
  End If

End Function

【问题讨论】:

  • /image 结尾的 URL 是否真的发送到图像?它可能期待像/image/img1.jpg?
  • 您不能将图像“放入”单元格 - 它只能定位在单元格“上方”
  • 快速随机问题 - 你可能是在用这个来学习吗?我只是问一下,因为您也可以在将鼠标悬停在单元格上之前不显示图像的地方执行此操作。

标签: vba excel


【解决方案1】:

给你:

Public Function getImage2(ByVal name As String) As String

  Dim imgURL As String
  Dim x&, y&, wdth&, hght& ' using "&" is the same as "As Long"
  Dim cellFunctionRunsOn As Range
  Dim img

  Set cellFunctionRunsOn = Columns(1).Find(what:=name)

  Dim XMLhttp: Set XMLhttp = CreateObject("MSXML2.ServerXMLHTTP")

  XMLhttp.setTimeouts 1000, 1000, 1000, 1000

  imgURL = "http://cactus.nci.nih.gov/chemical/structure/" + name + "/image"


  XMLhttp.Open "GET", imgURL, False

  XMLhttp.send

  If XMLhttp.Status = 200 Then

   'It exists so get the image
    x = Range(cellFunctionRunsOn.Offset(0, 1).Address).Left
    y = Range(cellFunctionRunsOn.Offset(0, 1).Address).Top
    wdth = Range(cellFunctionRunsOn.Offset(0, 1).Address).width
    hght = Range(cellFunctionRunsOn.Offset(0, 1).Address).height

    Set img = ActiveSheet.Shapes.AddPicture(Filename:=imgURL, linktofile:=msoFalse, savewithdocument:=msoTrue, Left:=x, Top:=y, _
        width:=wdth, height:=hght)
    img.Placement = xlMoveAndSize

  Else

  End If

End Function

这将获取您的图像,然后将其“放入”单元格中。

注意:正如@TimWilliams 所提到的,从技术上讲,您不能将其放入单元格中。上面所做的是,它获取您的 Image 并将其调整为与单元格相同的高度和宽度。因此,如果您想要更大的图像,则将单元格尺寸更大。

【讨论】:

  • 仅供参考 - 您只需要发出 HEAD 请求来检查内容是否可用:GET 将获取整个响应,但 HEAD 只会为您获取包括“200 OK”在内的标头。节省了每个结构的双重请求。
  • @TimWilliams - 对于 VB 的这种互联网使用,我非常喜欢......所以如果我只想使用 HEAD,我是否只需将 GET 替换为HEAD 这里:XMLhttp.Open "GET", imgURL, False ?
  • @BruceWayne - 是的 - 这就是你需要做的。例如。 jpsoftwaretech.com/vba/validate-url
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 2020-09-24
相关资源
最近更新 更多