Excel VBA:循环Web查询

时间:2011-07-13 09:11:16

标签: excel excel-vba excel-web-query vba

我有一个包含100,000个URL的列表,我需要通过API调用来解析它们。我已将它们分类为600多个连接字符串的列表,每个字符串包含200个URL - 准备好进行解析。

我编写了下面的代码来循环该过程,将返回的有关URL的信息放在C列的最后一行,一次一个。然而,我的循环似乎被打破了,我不知道为什么(看着它太久),但我怀疑这是一个菜鸟的错误。在完成前两个连接字符串(400个URL后,它开始重写第200行周围的信息,只处理第一个字符串。

代码如下,任何帮助将不胜感激。遗憾的是,我无法分享我试图解析的网址,因为它是由我的雇主建立的专有系统,不供公众使用。

Sub APIDataProcess()

    Dim lURLsLastRow As Long
    Dim lDataSetLastRow As Long
    Dim rngURLDataSet As Range
    Dim sURLArray As String
    Dim lURLArrayCount As Long
    Dim rngArrayCell As Range

    lURLsLastRow = Cells(Rows.Count, 1).End(xlUp).Row
    lDataSetLastRow = Cells(Rows.Count, 3).End(xlUp).Row

    Set rngURLDataSet = Range("A1:A" & lDataSetLastRow)

    lURLArrayCount = Range("B1").Value ' placeholder for count increments
    sURLArray = Range("A" & lsURLArrayCount).Value


    For Each rngArrayCell In rngURLDataSet

        If lsURLArrayCount <= lURLsLastRow Then
            With ActiveSheet.QueryTables.Add(Connection:="URL;http://test.test.org/test.php", Destination:=Range("C" & lDataSetLastRow))
                .PostText = "urls=" & sURLArray
                .RowNumbers = False
                .FillAdjacentFormulas = False
                .PreserveFormatting = True
                .RefreshOnFileOpen = False
                .BackgroundQuery = False
                .RefreshStyle = xlOverwriteCells
                .SavePassword = False
                .SaveData = True
                .AdjustColumnWidth = True
                .RefreshPeriod = 0
                .WebSelectionType = xlEntirePage
                .WebFormatting = xlWebFormattingNone
                .WebPreFormattedTextToColumns = True
                .WebConsecutiveDelimitersAsOne = True
                .WebSingleBlockTextImport = False
                .WebDisableDateRecognition = False
                .WebDisableRedirections = False
                .Refresh BackgroundQuery:=False
            End With
            lURLArrayCount = lURLArrayCount + 1
            Range("B1").Value = lURLArrayCount

            Application.Wait Now + TimeValue("00:01:00")

        Else
            Exit Sub

        End If

    Next rngArrayCell

End Sub

1 个答案:

答案 0 :(得分:0)

很久以前你可能已经解决了自己的问题,但由于这个问题仍然存在,我将继续解决。

我假设意图是B1最初为1,然后在处理每一行后逐步执行。这将允许您停止宏并继续前一次运行所处的位置。

但你不要那样使用B1或lURLArrayCount。您检查的范围始终是A1到Amax。您执行lURLArrayCount并将其存储在B1中,但其值不会在循环中使用。

您在循环外设置sURLArray但在其中使用它。

循环是For Each rngArrayCell但你永远不会使用rngArrayCell。

添加结果后,不要执行lDataSetLastRow。