出错时为变量赋值

时间:2016-05-26 21:47:54

标签: vba excel-vba error-handling excel

我想要做的是,如果出现错误,某些值会被重置。类似的东西:

Dim r As Integer
Dim feeder As String
Dim origen As String

On Error GoTo errhandler:
For j=1 to 100
   r = Evaluate("=MATCH(1, (C:C=""" & feeder & """) * (D:D=""" & origen & """),0)")
Next j

Exit Sub

errhandler:
r = 0
End Sub

但如果出现错误,如何强制它返回For

2 个答案:

答案 0 :(得分:2)

而不是ErrHanlding,您可以使用IsError在错误上设置r的值:

Sub t1()
  Dim feeder As String
  Dim origen As String
  For j = 1 To 100
   Dim r As Variant
   If IsError(Evaluate("=MATCH(1, (C:C=""" & feeder & """) * (D:D=""" & origen & """),0)")) Then
    r = 0
   Else
    r = Evaluate("=MATCH(1, (C:C=""" & feeder & """) * (D:D=""" & origen & """),0)")
   End If
  Debug.Print r ' Just for you to check
 Next

End Sub

答案 1 :(得分:1)

只需使用Resume Next声明

即可
Dim r As Integer
Dim feeder As String
Dim origen As String

On Error GoTo errhandler:
For j=1 to 100
   r = Evaluate("=MATCH(1, (C:C=""" & feeder & """) * (D:D=""" & origen & """),0)")
Next j

Exit Sub

errhandler:
r = 0
resume Next

End Sub