错误处理问题

时间:2014-06-10 15:12:47

标签: loops excel-vba error-handling vba excel

使用我的函数(在更大的代码中)我想找到一个目标列名。在另一个代码中,我检查列名是否是取消按钮(我将相应地调整它)

但是我想制作一个for循环,1到5期间“如果你输入一个不正确的列名称,它会要求你重新提交。如果你按下取消它会退出函数并在那之后退出sub(我将解决这个问题)我自己)。

Function FindText(Target As String)
Dim Value
Dim x

GoTo StartLoop

StartLoop:
For x = 1 To 5

With Rows(1)
Err.Clear
On Error GoTo FindDoesNotExist
.Find(what:=Target, after:=.Cells(1, 1)).Activate
End With
FindText = ActiveCell.Column
Exit Function

FindDoesNotExist:
Target = InputBox("Please Enter Correct Value(Row Name)")
GoTo StartLoop
Next x

FindText = 10000
End Function

问题是我不知道如何清除错误,因此“错误GoTo”第二次不起作用。有人可以帮助修复此代码或使其更好(如果有一些我还不太了解的技巧吗?)

编辑:

新规是:

Function FindText(Target As String)

 Dim x
 Dim found As Range

'StartLoop:
For x = 1 To 5

    Set found = Rows(1).Find(what:=Target, after:=.Cells(1, 1))

    If found Is Nothing Then
        Target = InputBox("Please Enter Correct Value(Row Name)")
    Else
        found.Activate
        FindText = ActiveCell.Column
        Exit Function
    End If

    Next x

    FindText = 10000
End Function

在遇到after:=。Cells(1,1))区域后,它突出显示单元格并给出:错误:无效或不合格的引用。任何想法?

2 个答案:

答案 0 :(得分:0)

最好的方法是首先停止发生错误。像这样:

...
    Dim found As Range

StartLoop:
    For x = 1 To 5
        With Rows(1)     
            Set found = .Find(what:=Target, after:=.Cells(1, 1))
        End with

        If found Is Nothing Then
            MsgBox ("Can't find " & Target)
        Else
            found.Activate
            FindText = ActiveCell.Column
            Exit Function
        End If
...

希望这足以帮助您修复代码。

答案 1 :(得分:0)

嗯,有几件事:

  1. 您可能希望防止在With语句中抛出错误。这可能会导致一些奇怪的错误。所以,我会加入Rows(1)Find;我也会使用工作表名称对其进行限定,例如Sheet1.Rows(1).Find(...)

  2. 作为一般规则,当遇到这样的问题时,请尝试将代码拆分为较小的函数。在这种情况下,我能够创建一个封装错误处理的函数,因此问题不再是问题。

  3. 您希望尽可能避免使用ActivateSelect。在这种情况下,不需要它们,代码更清晰。

  4. 像这样:

    Function FindText(Target As String)
    
        FindText = 1000 ' set default return value
    
    
        Dim foundCell As Range
        Set foundCell = getCellInRow1ByText(Target)
    
        Dim x As Integer
        For x = 1 To 5
            If Not foundCell Is Nothing Then
                FindText = foundCell.Column
                Exit Function
            End If
            Target = InputBox("Please Enter Correct Value(Row Name)")
            Set foundCell = getCellInRow1ByText(Target)
        Next x
    End Function
    
    Private Function getCellInRow1ByText(ByVal Target As String) As Range
        On Error GoTo Catch
        Set getCellInRow1ByText = Sheet1.Rows(1).Find(what:=Target, after:=Sheet1.Rows(1).Cells(1, 1))
        Exit Function
    Catch:
        Set getCellInRow1ByText = Nothing '' not really needed, but explains what's happening
    End Function
    

    可能不需要进行错误处理,但我已将其包含在内,以便您学习该方法。

    顺便说一句,对于原始问题的严格答案,您可以尝试添加

    On Error GoTo 0