[英]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.