简体   繁体   中英

VBA To Search Specific Column in Excel

I am trying to search a specific column in Excel (Column K) using the below VBA code but when I run the macro it instead searches the whole sheet instead of the specified column.

The problem is it firstly finds 'mycell1' in an earlier column, ie in Column C instead of Column K which I don't want it to do.

I have also tried using 'xlByRows' in the 'Searchorder' which had the same issue.

Would greatly appreciate any help please

Thanks

Range("K:K").Select
Set foundcell1a = Selection.Cells.Find(What:=mycell1, After:=ActiveCell, LookIn:=xlValues, LookAt _
    :=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False)
Set foundcell1a = Cells.FindNext
If Not foundcell1a Is Nothing Then
foundcell1a.Activate
End If

Don't use .Select if you can possibly avoid it and most of the time, you can.

Try using With...End With constructs instead. Be as specific as you can with the object you want to operate on.

Sub SearchK()
Dim mycell1
Dim foundcell1a As Range

    mycell1 = 1
    With ActiveWorkbook.Worksheets("Sheet1").Range("K:K")
        Set foundcell1a = .Find(mycell1, .Cells(.Rows.Count, 1))
        Set foundcell1a = .FindNext(foundcell1a)
        If Not foundcell1a Is Nothing Then
            foundcell1a.Activate
        End If
    End With
End Sub

Without a With...End With , you would have to repeat all the object identifiers so:

 Set foundcell1a = .Find(mycell1, .Cells(.Rows.Count, 1))

Would have to be expressed as:

Set foundcell1a = ActiveWorkbook.Worksheets("Sheet1").Range("K:K").Find(mycell1, .Cells(.Rows.Count, 1))

When VBA is evaluating a command it needs to evaluate each property preceding a period (.) every time it encounters it. Using ActiveWorkbook.Worksheets("Sheet1").Range("K:K") gets rid of 4 periods so it runs faster too.

The Set foundcell1a = .Find(mycell1, .Cells(.Rows.Count, 1)) is saying find mycell1 after the last used cell in column K so it loops back to find the first instance in column K regardless of the active cell.

Try this:

With Range("K:K")
    Set LastCell = .Cells(.Cells.Count)
End With

Set FoundCell1a = Range("K:K").Find(mycell1, LastCell)
If Not FoundCell1a Is Nothing Then
    FirstAddr = FoundCell1a.Address
    Range(FirstAddr).Activate
End If

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM