循环执行:循环执行,没有执行错误

时间:2018-08-21 10:40:56

标签: excel vba excel-vba

当我有一个非常简单的do while语句时,以下代码提供了一个“没有执行错误的循环”。代码在没有它的情况下运行,但是不会遍历我从中提取数据的100行。

很明显,此问题是由于readystate dowhile造成的(如果我注释掉该代码,代码将运行),但是我不确定在没有IE的情况下该机制的工作原理。

有人能够解释我需要添加哪些附加的(?)代码行来阻止此错误?

Do While i < 100

    Set ie = CreateObject("InternetExplorer.Application")

    With ie
        .Navigate URLStart
        .Visible = True
        Do While .ReadyState <> 4: DoEvents: Loop

        Set doc = ie.Document

        With doc
            LicenceNO = "whatever"
            ActiveSheet.Range("C" & i).Value = LicenceNO
            LicenceName = "whatever"
            ActiveSheet.Range("D" & i).Value = LicenceName
            BusinessAddress = "whatever"
            ActiveSheet.Range("E" & i).Value = BusinessAddress
            AATOCategory = "whatever"
            ActiveSheet.Range("F" & i).Value = AATOCategory
        End With

        i = i + 1

Loop

谢谢!

1 个答案:

答案 0 :(得分:1)

通过一致的缩进,您可以看到丢失的End With

Do While i < 100

    Set ie = CreateObject("InternetExplorer.Application")

    With ie
        .Navigate URLStart
        .Visible = True
        Do While .ReadyState <> 4
            DoEvents
        Loop

        Set doc = ie.Document

        With doc
            LicenceNO = "whatever"
            ActiveSheet.Range("C" & i).Value = LicenceNO
            LicenceName = "whatever"
            ActiveSheet.Range("D" & i).Value = LicenceName
            BusinessAddress = "whatever"
            ActiveSheet.Range("E" & i).Value = BusinessAddress
            AATOCategory = "whatever"
            ActiveSheet.Range("F" & i).Value = AATOCategory
        End With

        i = i + 1

    'This line missing:
    End With

Loop