【问题标题】:How to handle error handling once only?如何只处理一次错误处理?
【发布时间】:2016-08-31 12:54:35
【问题描述】:

我只想捕获我的错误处理语句一次,如果它再次失败,则继续下一个。我不确定如何实现这一目标,但到目前为止,如果代码继续失败,我可以重新运行代码。原因是如果文件永远不存在,我不想陷入循环。这是我所拥有的:

....some code

TryAgain:

....
....
    If Not FileExists("C:\" & FileName) Then
         GoTo TryAgain >>> Only want to run this once if it fails again continue on down with the next section of codes.
    End If

 ....next code stuff....

【问题讨论】:

  • goto 是撒旦的产物。改用 porper 循环。

标签: vba error-handling


【解决方案1】:
.....Dim blnRetry as Boolean

blnRetry =true

TryAgain:
....
....
   If Not FileExists("C:\" & FileName) Then
         if blnRetry then 
               blnRetry=false
               GoTo TryAgain 
         end if
    End If

【讨论】:

    【解决方案2】:

    我对@9​​87654321@ 的规则是我只在On Error 语句中使用它。考虑使用Do..Loop 和计数器。这是一个例子

    Sub Test()
    
        Dim sFile As String
        Dim lTryCnt As Long
    
        Const lMAXTRYCNT As Long = 10
    
        Do
            sFile = InputBox("Enter file name")
            lTryCnt = lTryCnt + 1
        Loop Until sFile = "False" Or Len(Dir("C:\" & sFile)) > 0 Or lTryCnt >= lMAXTRYCNT
    
        Debug.Print sFile, lTryCnt
    
    End Sub
    

    sfile = "False" 是如果用户在输入框中单击取消。 Len(Dir()) 如果文件不存在,则返回零长度字符串。

    【讨论】:

    • 这比使用Goto好多
    猜你喜欢
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多