当找不到“什么”时,在Excel中捕获.find错误

时间:2017-03-02 20:32:14

标签: excel-vba vba excel

我有一个Excel VBA功能已经工作了很长时间。但是我发现当此代码中不存在i时:

Dim rowNum as Integer
for i = 1 to 20
    rowNum = Columns(SiteNumCol).Find(What:=i, LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False).row
    <other stuff>
Next i

返回错误。我尝试重构代码以包含一个检查:

    rowNum = Columns(SiteNumCol).Find(What:=i, LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False).row
    If Not rowNum = 0 Then
        <other stuff>
    End If
Next i

然而,它仍然在rownum =行出错。我以为这可能就像我在调用行号一样,所以尝试了这个测试:

test = Columns(NumCol).Find(What:=i, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
If Not test Is Nothing Then
    rowNum = Columns(NumCol).Find(What:=i, LookIn:=xlValues, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).row

现在,在带有424“需要对象”错误的If语句中出现错误;我认为这是因为'test'目前是双倍的,因为它在第一次迭代时出错。如果我将测试更改为= "0",则会经历迭代,直到找不到,然后失败,因为在test =由于良好的''91“对象变量未设置”

如何在找不到内容时成功捕获.find错误?

1 个答案:

答案 0 :(得分:2)

像这样。你非常接近,只是错过了我认为的那套。

Dim r As Range
Dim rowNum As Long
For i = 1 To 20
    Set r = Columns(SiteNumCol).Find(What:=i, LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
    If Not r Is Nothing Then rowNum = r.Row
    <other stuff>
Next i