0

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
  • What does Set sColumn = TargetRange.Cells.Find("This Column") give you? you also need to check if sColumn is nothing before assigning it to targetColumn Commented May 28, 2017 at 12:51
  • I just tested the code. it works for me. BTW .Find retains the last setting. Ensure you set all parameters. For exampleLookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False Commented May 28, 2017 at 12:55

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.