无法使用Excel VBA将文本分配给单元格

时间:2018-09-18 22:44:35

标签: excel vba 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

1 个答案:

答案 0 :(得分:0)

事物的结合。首先,您的循环是不必要的。我运行了您的代码,没有任何循环。即使有必要,也可能使用不当。

因此,假设您实际上不需要For...Next循环,则可以将0 index 编号用于{{1} },然后将单元格引用设置为等于该收集项的IE.Document.getElementsbyClassName("desktop-title-subcontent")属性。

这使我进入下一个问题,即您的单元格参考。 innerTextCells(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

可选

最后,我将研究使用Early Binding over late binding。它具有许多优点,并且可能显着提高速度。

您需要设置对Cells(2, "F").Value = IE.Document.getElementsByClassName _ ("desktop-title-subcontent")(0).innerText 的引用,并将Microsoft Internet Controls声明为IEInternetExplorer类型。但这不会破坏或破坏您的代码。