我知道这看起来很容易。我已经输入了一个代码来尝试让它工作,但遇到了一个问题。以下链接上的格式对于所有城市和州都是相同的。只要您可以输入城市名称(“City_Search”)和州名(“State_Search”),您就可以使用如下所示的信息访问该网站。
我附上了我在下面使用的公式。如果有人可以帮助我进行搜索,我将不胜感激。
Sub SearchBot1()
'dimension (declare or set aside memory for) our variables
Dim objIE As InternetExplorer 'special object variable representing the IE browser
Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
Dim HTMLinputs As MSHTML.IHTMLElementCollection
'initiating a new instance of Internet Explorer and asigning it to objIE
Set objIE = New InternetExplorer
'make IE browser visible (False would allow IE to run in the background)
objIE.Visible = True
'navigate IE to this web page (a pretty neat search engine really)
objIE.navigate "https://datausa.io/profile/geo/" & Range("City_Search").Value & "-" & Range("State_Search").Value
'wait here a few seconds while the browser is busy
Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
End Sub
我的想法是让我在 Excel 中输入任何城市,一旦我在宏上运行,它就会转到该站点并搜索城镇数据。我在下面添加了一个链接作为我在搜索时希望获得的页面的示例。
https://datausa.io/profile/geo/hoboken-nj/
最佳答案
您需要 连字符 标题中有空格的城市。 Counties 必须是正确的缩写,并且两者都区分大小写,即需要为 全部小写 .因此,如果缺少这些连字符,您需要使用 Replace
之类的函数添加这些连字符。在 vba 中,交换 Chr$(32)
带“-”或Chr$(45)
, 并且可能是 LCase$
转换为小写。
您还应该使用您打算使用的工作表完全限定范围。
单元格中的数据格式正确:
例如。与 los-angeles-ca
或 los-angeles-county-ca
在一个单元格中。
Option Explicit
Public Sub SearchBot1()
Dim objIE As InternetExplorer, aEle As HTMLLinkElement
Dim HTMLinputs As MSHTML.IHTMLElementCollection
Set objIE = New InternetExplorer
'e.g. https://datausa.io/profile/geo/los-angeles-ca/
With objIE
.Visible = True
.navigate "https://datausa.io/profile/geo/" & Range("City_Search").Value & "-" & Range("State_Search").Value
Do While .Busy = True Or .readyState <> 4: DoEvents: Loop
Stop
' .Quit '<== Uncomment me to close browser at end
End With
End Sub
添加连字符:
如果您有
los angeles
,而不是 los-angeles
,在一个单元格中:Replace$(Range("City_Search").Value, Chr$(32), Chr$(45))
小写和连字符:
为了真正安全起见,您也可以转换为小写字母以处理您引用的单元格中的任何大写字母,例如
对于
Los Angeles
使用:Replace$(LCase$(Range("City_Search").Value)
Option Explicit
Public Sub SearchBot1()
Dim objIE As InternetExplorer, aEle As HTMLLinkElement
Dim HTMLinputs As MSHTML.IHTMLElementCollection, ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set objIE = New InternetExplorer
'e.g. https://datausa.io/profile/geo/los-angeles-ca/
With objIE
.Visible = True
.navigate "https://datausa.io/profile/geo/" & ws.Range("City_Search").Value & "-" & ws.Range("State_Search").Value
Do While .Busy = True Or .readyState <> 4: DoEvents: Loop
Stop
' .Quit '<== Uncomment me to close browser at end
End With
End Sub
这会让你进入页面。那你怎么办……
关于vba - 如何使用 VBA 输入网站地址并进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51297332/