1

I want to be able to set a range for the second cell under the column header I am searching for to the bottom of the column. I don't want to select the entire column, but just the used range starting from the second cell (not including the header).

I was able to write some code to find the header, but I'm having some issues converting the cell address (string) to a range and then selecting the used range for the rest of that column. Here is what I am so far:

Sub colRange()

Dim ws As Worksheet
Dim hostCellRange As Range

Set ws = Worksheets("Sheet1")

With ws
    With .Range("A1", .Cells(1, .Columns.Count).End(xlToLeft))
        Set cfind = .Find(What:="host", LookIn:=xlValues, lookat:=xlWhole)
        If Not cfind Is Nothing Then
            hostCell = cfind.Address
            Set hostCellRange = ws.Range(hostCell)
        End If
    End With
End With


End Sub

Thank you for your help!

1
  • will you have blank cells in your range? Commented Nov 24, 2017 at 16:00

2 Answers 2

2

The correct way to do it will be

Option Explicit

Sub colRange()
    Dim ws As Worksheet
    Dim hostCellRange As Range, cfind As Range
    Dim lRow As Long, lCol As Long

    Set ws = Worksheets("Sheet1")

    With ws
        With .Range("A1", .Cells(1, .Columns.Count).End(xlToLeft))
            Set cfind = .Find(What:="host", LookIn:=xlValues, lookat:=xlWhole)
            If Not cfind Is Nothing Then
                '~~> Find the column number
                lCol = cfind.Column
                '~~> Find the last row in that column
                lRow = ws.Range(Split(Cells(, lCol).Address, "$")(1) & ws.Rows.Count).End(xlUp).Row
                '~~> Create the range
                Set hostCellRange = .Range(cfind.Offset(1, 0), cfind.Offset(lRow - 1, 0))
                Debug.Print hostCellRange.Address
            End If
        End With
    End With
End Sub

Example 1

enter image description here

Example 2

enter image description here

Interesting Read on how to find the last row correctly

Sign up to request clarification or add additional context in comments.

1 Comment

Hey Siddharth, thank you for taking the time to explain the code as well! I will be using this! I appreciate the help!
1

Try setting hostCellRange using the Offset from cfind, you don't need the Address for that.

If Not cfind Is Nothing Then
    Set hostCellRange = .Range(cfind.Offset(1, 0), cfind.End(xlDown))
End If

Note: cfind.End(xlDown) will work with range without empty cells in the middle.

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.