VBA:访问崩溃时调用函数没有错误

时间:2017-06-19 11:27:15

标签: vba access-vba

调用此

时遇到问题
Public IE As InternetExplorer
Private Declare Sub Sleep Lib "kernel32" (ByVal lngMilliSeconds As Long)
Dim el As Object

Public Function IEClick(Idstr As String)
Do
    Set el = Nothing
    On Error Resume Next
    Set el = IE.Document.getElementById(Idstr)
    On Error GoTo 0
    DoEvents
    Sleep (100)
Loop While el Is Nothing
Sleep (1000)
IE.Document.getElementById(Idstr).Click
End Function

它循环为真,直到它找到正确的元素。当像这样调用Function时,我在此行IEClick Str(Item)上没有错误消息崩溃。

For Each Item In coll
    IEClick Str(Item)
    p = p + 1
Next

这是完整的代码。

Public Sub AutoExtract()
Dim ProgressBar_Extract As Object
Dim coll As Collection
Set coll = New Collection

'/////////////////controls in order///////////////
With coll
    .Add "ctl00_cmdCustom"
    .Add "chkAll"
    .Add "ctl00_cmdContinue"
End With
Me.ProgressBar_Extract.Max = coll.Count
'////////////////////start ie//////////////////
Set IE = New InternetExplorerMedium
With IE
    '.AddressBar = False
    '.MenuBar = False
    .Navigate ("*****")
    .Visible = True
End With
'//////////////////////Start Automation///////////////////
For Each Item In coll
    IEClick Str(Item)
    p = p + 1
Next
MsgBox "Extract Complete"
End Sub

我把它缩小到IEClick Str(Item)。调试时如果我停下来然后走到下一行就会崩溃。

2 个答案:

答案 0 :(得分:0)

1)不要使用Item作为变量名,它是VBA中的保留字(Collection.Item)

2)将Option Explicit放在每个模块的顶部。
它强制执行变量声明,并在编译时报告未声明或拼写错误的变量/常量。 要在新模块中自动执行此操作,请在VBA编辑器中设置Require Variable Declaration选项。

3)我无法重现崩溃,但在使用字符串参数调用Str()时出现运行时错误。

试试这个:

Option Explicit

Public Sub TestCrash()

    Dim coll As Collection
    Dim vItem As Variant

    Set coll = New Collection

    With coll
        .Add "ctl00_cmdCustom"
        .Add "chkAll"
        .Add "ctl00_cmdContinue"
    End With

    For Each vItem In coll
        ' Gives Runtime error 13 "Type mismatch"
        ' Debug.Print Str(vItem)

        ' This works
        Debug.Print vItem
    Next

End Sub

如果有效,请调整您的代码。

答案 1 :(得分:0)

Str()非常容易出错,有时最好使用cstr()来使我的访问崩溃