[英]Can't assign text to cell with Excel VBA
我正在尝试从Google抓取邮政编码。 我一直在尝试将innertext
放入单元格中,但我认为我可能在第二行到最后一行遇到变量不匹配的情况。
'This Must go at the top of your module. It's used to set IE as the active window
Sub Automate_IE_Enter_Data()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
Dim HWNDSrc As Long
Dim adds As Variant, add As Variant
Dim addt As String
'Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True
'Define URL
URL = "https://www.google.com/search?ei=djKhW7nELYqs8AO96baoAw&q=1000 Westover Rd kansas city, Mo"
'Navigate to URL
IE.Navigate URL
' Statusbar let's user know website is loading
Application.StatusBar = URL & " is loading. Please wait..."
' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertantly skipping over the second loop)
Do While IE.ReadyState = 4: DoEvents: Loop
Do Until IE.ReadyState = 4: DoEvents: Loop
'Webpage Loaded
Application.StatusBar = URL & " Loaded"
'Get Window ID for IE so we can set it as activate window
HWNDSrc = IE.Hwnd
'Set IE as Active Window
'SetForegroundWindow HWNDSrc
Debug.Print "ihgc"
'Unload IE
endmacro:
Set adds = IE.Document.getElementsbyClassName("desktop-title-subcontent")
For Each add In adds
Debug.Print add.innertext
Next
Cells(2, f).Value = add.innertext
End Sub
几件事。 首先,您的循环是不必要的。 我运行了您的代码,没有任何循环。 即使有必要,也可能使用不当。
因此,假设您实际上不需要For...Next
循环,则可以将索引号0
用于IE.Document.getElementsbyClassName("desktop-title-subcontent")
集合,然后设置您的单元格引用等于该收集项的innerText
属性。
这将我带入下一个问题,即您的单元格参考。 Cells(2, f)
, f
不是声明的变量。 如果您实际想使用列“ F”,那么您需要将“ F”用双引号引起来:
Cells(2, "F")
或使用列索引6
, Cells(2, 6)
因此,请替换整个部分:
Set adds = IE.Document.getElementsbyClassName("desktop-title-subcontent")
For Each add In adds
Debug.Print add.innertext
Next
Cells(2, f).Value = add.innertext
有了这个:
Cells(2, "F").Value = IE.Document.getElementsByClassName _
("desktop-title-subcontent")(0).innerText
最后,我将研究使用Early Binding而不是Late binding 。 它具有许多优点,可能会显着提高速度。
您将需要设置对Microsoft Internet Controls
的引用,并将IE
声明为InternetExplorer
vs Object
类型。 但这不会破坏或破坏您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.