How to find a value in an excel column by vba code Cells.Find

前端 未结 4 1814
情歌与酒
情歌与酒 2020-11-30 03:38

I have to find a value celda in an Excel sheet. I was using this vba code to find it:

Set cell = Cells.Find(What:=celda, After:=ActiveCell,          


        
4条回答
  •  借酒劲吻你
    2020-11-30 04:20

    I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

    Set cell = ActiveSheet.Columns("B:B").Find( _
        What:=celda, _
        After:=ActiveCell _
        LookIn:=xlFormulas, _
        LookAt:=xlWhole, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, _
        MatchCase:=False, _
        SearchFormat:=False _
    )
    
    If cell Is Nothing Then
        'do something
    Else
        'do something else
    End If
    

    I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

    Dim rng as Range
    Dim cell as Range
    Dim search as String
    
    Set rng = ActiveSheet.Columns("B:B")
    search = "String to Find"
    Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)
    
    If cell Is Nothing Then
        'do something
    Else
        'do something else
    End If
    

    I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

提交回复
热议问题