0

I need to find out the column that is the last column in a range that is defined with:

Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange
user2021539
  • 949
  • 3
  • 14
  • 31

2 Answers2

1

First things first

Never use UsedRange to set your range. I have explained it HERE as to why you shouldn't use UsedRange

Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange

Find the Last Column that has data and the Last Row which has data and then set your range. So your question of finding the last column from the range will not arise. Here is an example

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lRow As Long, lCol As Long

    '~~> Set your worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            '~~> Find Last Row
            lRow = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row

            '~~> Find Last Column
            lCol = .Cells.Find(What:="*", _
                   After:=.Range("A1"), _
                   Lookat:=xlPart, _
                   LookIn:=xlFormulas, _
                   SearchOrder:=xlByColumns, _
                   SearchDirection:=xlPrevious, _
                   MatchCase:=False).Column
        Else
            lRow = 1: lCol = 1
        End If

        '~~> Set your range
        Set rng = .Range(.Cells(1, 1), .Cells(lRow, lCol))

        Debug.Print rng.Address
    End With
End Sub
Community
  • 1
  • 1
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
0

Use End(xlToRight) with an activecell.

Marshall
  • 99
  • 5