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