对于罗嗦的标题抱歉...
我在一长串VBA代码中有一个(第二个)循环。循环是这样的:
Do While counterB < 40000
On Error Resume Next
AppActivate "Oracle Fusion Middleware Forms Services"
If Err.Number <> 0 Then
counterB = counterB + 100
Sleep 100
Else
counterB = counterB + 40001
End If
Loop
现在,有一个类似的循环可以在此之前检查一个不同的程序,它运行得很好。检查程序是否打开,增加其计数器(两个循环的计数器具有不同的名称),再次检查,增量,冲洗 - 和 - 重复,最终找到其程序,启动其循环并继续VBA代码。
但是这第二个循环......它只是循环。结束......它进入If/Else
就好了(所以,是看到或看不到AppActivate
中调用的程序),但是{{1声明并不承认 counterB 大于40,000。
有谁看到我做错了什么......? 提前谢谢。
答案 0 :(得分:4)
只是解释integer
内容 CLR 和 Jeeped 正在谈论:
VBA中的整数是2个字节并且有符号(可以有负值),因此最大值是32767.如果您尝试将更大的值写入其中,则会出现运行时错误6(溢出)并且值仍然存在不变。由于存在on error resume next
,因此未显示错误,该值保持最大值32767并且永远不会达到40000的值 - 您将陷入无限循环。
如果您的代码中确实需要on error resume next
,则应检查Err.Number以获取您期望的特定值(并重新添加错误或显示MsgBox或类似内容)。
您的代码可能如下所示:
Do While counterB < 40000
Dim saveError As Long
On Error Resume Next
AppActivate "Oracle Fusion Middleware Forms Services"
saveError = Err.Number
On Error GoTo 0
If saveError <> 0 Then
If Err.Number = <ENTER YOUR SPECIFIC ERROR CODE> Then
counterB = counterB + 100
Sleep 100
Else
Err.Raise saveError
End If
Else
counterB = counterB + 40001
End If
Loop
答案 1 :(得分:1)
虽然讨论和接受的答案解释了OP代码失败的原因,但OP采取的整个方法并不理想。
我就是这样做的
Sub Demo()
Dim saveError As Long
Dim counterB As Long
Dim AppActivated As Boolean
For counterB = 1 To 400
On Error Resume Next
AppActivate "Oracle Fusion Middleware Forms Services"
saveError = Err.Number
On Error GoTo 0
If saveError = 0 Then
AppActivated = True
Exit For
Else
Select Case saveError
'<ENTER YOUR SPECIFIC ERROR CODES HERE>
Case 5, 6, 7 ' for example
Sleep 100
Case Else
Err.Raise saveError
End Select
End If
Next
If Not AppActivated Then
' Loop timed out. What Now?
Else
' App is activated
' More code...
End If
End Sub
答案 2 :(得分:0)
假设@Jeeped提到,counterB
不是整数..请尝试以下方法:
Do While counterB < 40000
On Error Resume Next
AppActivate "Oracle Fusion Middleware Forms Services"
If Err.Number <> 0 Then
counterB = counterB + 100
Sleep 100
Err.Clear
Else
counterB = counterB + 40001
End If
Loop