对所有行运行的代码的修正

时间:2017-05-09 15:09:12

标签: excel vba excel-vba

我目前对excel电子表格上的一组数据进行了以下编码:

    Sub DemoMutual2()
Dim URL As String
Dim ieDoc As Object, dObj As Object
Dim cel As Range

    URL = Range("G2").Value
    With CreateObject("InternetExplorer.Application")
        .Visible = False
        .Navigate URL

        Do Until .ReadyState = 4: DoEvents: Loop

        Set ieDoc = .Document
        Set dObj = ieDoc.getElementsByClassName("_50f3")
        [K2].Value = Split(ieDoc.getElementsByClassName("_50f3")(0).innerText, " ")(0)
        For i = 0 To dObj.Length - 1
            If InStr(1, dObj(i).getElementsByTagName("a")(0).innerText, "since") Then
                [M2].Value = Trim(Split(dObj(i).getElementsByTagName("a")(0).innerText, "since")(1))
            End If
        Next
        .Quit
    End With
    Set ieDoc = Nothing
    Set dObj = Nothing

End Sub

目前,这仅适用于基于单元格G2中的URL的一行。我希望这段代码运行的是G列(G2,G3,G4等)中的所有URL,并在代码中指定的单元格中返回所需的结果(K2,K3,K4等,M2,M3,M4)等等)。

所以要在G2中搜索URL并在K2和M2中返回结果 然后是G3,结果是K3和M3等等。

目前这对于一行完美无缺,但我正在努力改变它,所以我可以为多行做到这一点。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

这是如何运作的?

Sub DemoMutual2()
Dim URL     As String
Dim ieDoc As Object, dObj As Object
Dim cel     As Range
Dim lastRow As Long, i As Long, iRow As Long

lastRow = Cells(Rows.Count, 7).End(xlUp).Row

For iRow = 2 To lastRow
    URL = Range("G" & iRow).Value
    With CreateObject("InternetExplorer.Application")
        .Visible = False
        .Navigate URL

        Do Until .ReadyState = 4: DoEvents: Loop

        Set ieDoc = .Document
        Set dObj = ieDoc.getElementsByClassName("_50f3")
        Cells(iRow, 11).Value = Split(ieDoc.getElementsByClassName("_50f3")(0).innerText, " ")(0)
        For i = 0 To dObj.Length - 1
            If InStr(1, dObj(i).getElementsByTagName("a")(0).innerText, "since") Then
                Cells(iRow, 13).Value = Trim(Split(dObj(i).getElementsByTagName("a")(0).innerText, "since")(1))
            End If
        Next i
        .Quit
    End With
    Set ieDoc = Nothing
    Set dObj = Nothing
Next iRow

End Sub

注意:最好将IE.QuitSet ieDoc = Nothing行移到整个循环之外以获得性能,但如果没有太多行,这可能会有效。