Excel VBA Find Method for specific column

2019-09-17 23:56发布

VBA find method seems to fail when I am trying to search for the value in specific column. This code

Sub TargetR()
Dim CLL As Range
Dim TargetRange As Worksheet
Dim R As Range

Set CLL = ThisWorkbook.Worksheets(1).Range("J29")
Set TargetRange = ThisWorkbook.Worksheets(1)
Set R = TargetRange.Cells.Find(CLL.Value)

If Not (R Is Nothing) Then
    Debug.Print R.Address
Else: Debug.Print "Empty"
End If

End Sub

works perfectly. While the search limited by the column with keyword header fails:

Sub Target()
Dim CLL As Range
Dim TargetRange As Worksheet
Dim targetColumn As Range
Dim sColumn As Range


Dim R As Range

Set CLL = ThisWorkbook.Worksheets(1).Range("J29")
Set TargetRange = ThisWorkbook.Worksheets(1)
Set sColumn = TargetRange.Cells.Find("This Column")
Set targetColumn = sColumn.EntireColumn
Set R = targetColumn.Cells.Find(CLL.Value)

If Not (R Is Nothing) Then
    Debug.Print R.Address
Else: Debug.Print "Empty"
End If

End Sub

Specifying search direction through xlByColunm does not help

2条回答
Summer. ? 凉城
2楼-- · 2019-09-18 00:23

Try the code below (explanation inside the code as comments):

Option Explicit

Sub Target()

Dim CLL As Range
Dim TargetRange As Worksheet
Dim sColumn As Range
Dim R As Range

Set CLL = ThisWorkbook.Worksheets(1).Range("J29")
Set TargetRange = ThisWorkbook.Worksheets(1)

Set sColumn = TargetRange.Cells.Find("This Column")
If Not sColumn Is Nothing Then ' <-- make sure Find was successful
    Set R = sColumn.EntireColumn.Find(what:=CLL.Value, LookIn:=xlValues, lookat:=xlWhole)        
    If Not R Is Nothing Then
        Debug.Print R.Address
    Else: Debug.Print "Empty"
    End If
Else ' Find failed to find "This Column"
    MsgBox "Unable to find 'This Column'"
End If 

End Sub
查看更多
疯言疯语
3楼-- · 2019-09-18 00:32

As I figured out, Find method do not work correctly if value that needs to be found contained in merged cell, and Find methoud applied only for the leftmost column, that contain part of that merged cell. For my VBA code to work properly, some additional merge check , and subsequent extension of search area was the answer

If sColumn.MergeCells Then
                Set sColumn = Column.Resize(,Column.MergeArea.Columns.Count)
查看更多
登录 后发表回答