loops - 错误处理问题

标签 loops excel error-handling vba

通过我的函数(在更大的代码内),我想找到一个目标列名称。在另一个代码中,我检查列名称是否为“取消”按钮(并且我也会相应地对其进行调整)

但是我想进行一个1到5的for循环,在此期间“如果输入不正确的列名,它将要求您重新提交。如果按Cancel,它将退出函数并在此之后退出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

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

编辑:

新代码是这样的:
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))区域后,它突出显示单元格并给出:错误:无效或不合格的引用。有任何想法吗?

最佳答案

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

...
    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
...

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

关于loops - 错误处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24144612/

相关文章:

c - 如何将字符串中的元音更改为符号?

vba - 从 Excel 保存 csv 会丢失小数点精度

Excel 宏在 Catia V5 中不起作用

c++ - 错误 : redefinition of class [class name]

r 比较 2 个文件与 for 循环并划分某些列

php - 在wordpress中获取帖子的作者ID

javascript - 从内部循环输出多个单元格

python - 从 Excel 中的模块获取代码

c# - 简单的Excel创建不会打开文件已损坏

error-handling - RxAndroid-使用Zip运算符处理错误