Use Range Find Method in a specific column

隐身守侯 提交于 2019-12-04 04:42:54

问题


I have been tinkering with this for a while now, I have the below code working but it searches more than I would like it to. I would like it to just search column C and not the entire sheet. I have tried changing out the Cells.Find to Range("C1:C10000").Find but it returns no matches.

Really stumped on this one.

Dim r As Range

Set r = Sheets("State Agent List").Range("C1:C10000").Find(What:=ComboBox22.Value, _
            After:=ActiveCell, LookAt:=xlPart, SearchOrder:=xlByRows)

If Not r Is Nothing Then
    r.Select
    ActiveWindow.ScrollRow = ActiveCell.Row
Else
    MsgBox "Location not listed."
End If    

回答1:


Your problem is the use of ActiveCell which if happens to be not within C1:C10000 will return nothing. Try this:

Dim searchRng As Range: Set searchRng = Sheets("State Agent List").Range("C1:C10000")
Dim r As Range
Set r = searchRng.Find(What:=ComboBox22.Value, After:=searchRng(searchRng.Count))

The argument searchRng(searchRng.Count) pertains to the last cell of the Range you're working on. It works but it can be written explicitly this way:

searchRng.Cells(searchRng.Cells.Count)

Why do we need to set the After argument to the last cell?
Main reason is for the search to begin from the very first cell. HTH




回答2:


I would try it like this

  • ensure you start searching from C1 in case there are multiple matches (given you are setting a scrollwindow)
  • xlFormulas finds cells in hidden rows, xlValues skips them
  • no need for the Select

    Dim rng1 As Range
    Set rng1 = Sheets("State Agent List").Range("C1:C10000").Find(CStr(ComboBox22.Value), [c10000], xlFormulas, xlPart, , xlNext)
    
    If Not rng1 Is Nothing Then
        ActiveWindow.ScrollRow = rng1.Row
    Else
        MsgBox "Location not listed."
    End If
    


来源:https://stackoverflow.com/questions/28333965/use-range-find-method-in-a-specific-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!