错误使用宏将谷歌的第一个图像链接添加到Excel

时间:2017-08-21 09:49:46

标签: excel vba excel-vba

我正在使用以下代码在B1中输入Google的第一张图片链接 对于A1中的某些值。

Public Sub Test()
    Dim IE As InternetExplorer
    Dim HTMLdoc As HTMLDocument
    Dim imgElements As IHTMLElementCollection
    Dim imgElement As HTMLImg
    Dim aElement As HTMLAnchorElement
    Dim N As Integer, I As Integer
    Dim Url As String, Url2 As String
    Dim LastRow As Long
    Dim m, sImageSearchString

    LastRow = Range("A" & Rows.Count).End(xlUp).Row

    For I = 1 To LastRow
        Url = "http://www.google.co.in/search?q=" & Cells(I, 1) & "&source=lnms&tbm=isch&sa=X&rnd=1"
        Set IE = New InternetExplorer

        With IE
            .Visible = False
            .Navigate Url 'sWebSiteURL

            Do Until .readyState = 4: DoEvents: Loop
                'Do Until IE.document.readyState = "Complete": DoEvents: Loop

            Set HTMLdoc = .document

            Set imgElements = HTMLdoc.getElementsByTagName("IMG")

            N = 1
            For Each imgElement In imgElements
                If InStr(imgElement.src, sImageSearchString) Then
                    If imgElement.ParentNode.nodeName = "A" Then
                        Set aElement = imgElement.ParentNode

                        Url2 = imgElement.src
                        N = N + 1
                    End If
                End If
            Next

            Cells(I, 2) = Url2

            IE.Quit
            Set IE = Nothing
        End With
    Next
End Sub

但是我收到以下错误,你能告诉我吗?

我正在使用Windows 10,Excel 365

enter image description here

1 个答案:

答案 0 :(得分:0)

在VBA菜单中 - 工具 - 参考 - 勾选MS Internet Controls。

或者

使用后期绑定

Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")