通过UDF获取Google搜索的第一个结果

时间:2013-11-26 09:59:37

标签: vba excel-vba excel

Santosh在以下link上有一个很棒的答案(vba代码),它在Google中搜索文本并捕获excel中的第一个URL结果,无论如何,这可以被用作/转换为UDF,从而公式可以是=Googlefirsturl(A1)A1具有需要搜索的文本。

编辑:可以忽略第2列数据(名称)

1 个答案:

答案 0 :(得分:3)

如果你真的需要它作为一个功能,那么

enter image description here

Option Explicit

Function GoogleFirstUrl(search As String) As String

    Dim i As Long
    Dim url As String, lastRow As Long
    Dim XMLHTTP As Object, html As Object, objResultDiv As Object, objH3 As Object, link As Object

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

    Dim cookie As String
    Dim result_cookie As String

    DoEvents
    url = "https://www.google.co.in/search?q=" & search & "&rnd=" & WorksheetFunction.RandBetween(1, 10000)

    Set XMLHTTP = CreateObject("MSXML2.serverXMLHTTP")
    XMLHTTP.Open "GET", url, False
    XMLHTTP.setRequestHeader "Content-Type", "text/xml"
    XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"
    XMLHTTP.send

    Set html = CreateObject("htmlfile")
    html.body.innerHTML = XMLHTTP.ResponseText
    Set objResultDiv = html.getelementbyid("rso")
    Set objH3 = objResultDiv.getelementsbytagname("H3")(0)
    Set link = objH3.getelementsbytagname("a")(0)

    GoogleFirstUrl = link.href

End Function

注意:你不能使用UDF修改其他单元格,这样你一次只能返回一个用于输入公式的单元格 - 我选择了你命名的URL你的功能