0

我在 VBA for excel 中有下一个代码的第一个版本

Function findCell(celda As String, rnc As String) As String

    Dim cell As Range
    Dim pos As String

    Range("A2").Select

    Set cell = Cells.Find(What:=celda, After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False)

    If cell Is Nothing Then
        pos = 0
    Else
        pos = cell.row
    End If

    findCell = pos

End Function

该函数接收一个字符串并返回列数中的位置,但是在我更改参数之后,因为我必须找到单元格的完整包含。我将值 lookAt 从x1Part更改为x1Whole

    Set cell = Cells.Find(What:=celda, After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False)

当我尝试运行宏有时不起作用并向我显示该值x1Whole,但是当我从编辑器运行时。

4

1 回答 1

1

如果您在公式中寻找一个字符串作为 xlPart,您总是从您的函数本身获取字符串(一个好主意,顺便说一句)。xlWhole 会有一个问题:可能存在不匹配的情况(如果公式是工作表中唯一的内容,那就是这种情况)。Find如果没有找到任何内容,将给出错误,并且公式结果将为#N/A。下面是带有错误处理的代码,结果为 0 表示不匹配。

Function findCell(celda As String, rnc As String) As String

    Dim cell As Range
    Dim pos As String

On Error GoTo Nomatch

    Set cell = Cells.Find(What:=celda, After:=Range("A2"), LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False)

Nomatch:

    If cell Is Nothing Then
        pos = 0
    Else
        pos = cell.Row
    End If

    findCell = pos

End Function

另外,我删除了Select("A2"),并将其移至After:=Range("A2").

于 2012-11-26T20:50:01.647 回答