Getting attribute values in VBA

2019-02-19 09:56发布

问题:

I need to make a VBA file that will read a webpage and return the value of the SRC attribute of the IMG tag. I wasn't able to make the last step work. Can you guys help me?

<html>
<body>
<img src="image.jpg">
</body>
</html>

===Edit=== I managed to return the attribute object. Now I need to return its value

Option Compare Database

Sub AcessaPagina()
    Dim ie As InternetExplorer
    Dim test As String
    Dim obj As Object

    Set ie = New InternetExplorer
    ie.Navigate "http://www.google.com.br"
    MsgBox ie.Document.getElementsByTagName("img").Item(0).Attributes("src")
    ie.Visible = True 
End Sub

That's what I have at the moment.

回答1:

There is no method called "getElementByTagName" -- it's called getElementsByTagName (note the s because it is a collection)

The Document Object returns a collection of all the img tags in the source. So you can iterate it like this:

Sub AcessaPagina()
    Dim ie As Object ' InternetExplorer
    Dim images As Object ' MSHTML.IHTMLElementCollection
    Dim image As Object ' MSHTML.IHTMLElement

    Set ie = CreateObject("InternetExplorer.Application")
    ie.navigate "http://www.google.com.br"
    Set images = GetAllImages(ie)

    For Each image In images
      Debug.Print image.getAttribute("src")
    Next image

End Sub

Function GetAllImages(ie As Object) As Object
  Set GetAllImages = ie.document.images
End Function