找到非价值的第一个分支

时间:2016-08-12 08:49:32

标签: excel excel-vba vba

在查找包含测试“DID”的单元格的典型查找函数中,代码看起来像

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

但是,如果我试图找到除“DID”以外的任何其他内容的第一个实例,该怎么办?我试过以下但似乎没有用。

Set cell = Selection.Find(What <> "DID", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)

1 个答案:

答案 0 :(得分:1)

您可以同时使用.Find.FindNext。这是你想要的吗?

Sub Sample()
    Dim aCell As Range, bCell As Range

    Set aCell = Cells.Find(What:="*", LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then
        Set bCell = aCell

        If aCell.Value <> "DID" Then
            MsgBox aCell.Address
            Exit Sub
        End If

        Do
            Set aCell = Cells.FindNext(After:=aCell)

            If Not aCell Is Nothing Then
                If aCell.Address = bCell.Address Then Exit Do
                If aCell.Value <> "DID" Then
                    MsgBox aCell.Address
                    Exit Do
                End If
            End If
        Loop
    End If
End Sub