• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Error in Range - Sort with last row last column

bvanscoy678

Member
Hello,


I may be making this more complicated than it should be. I want to sort my table based on the F Column which will have a dynamic range (also could have empty columns within the table).


I think my error is with ws.Range("rng")


Area of Code with Error:

' ws.Range("L2").Select


ws.Range("rng").Sort Key1:=Range("L2"), Order1:=xlAscending, Header:=

xlGuess , OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _

DataOption1:=xlSortNormal'


Thanks for any help. Brent


'Option Explicit


Sub Sample()


'//////code from: Stackoverflow

Dim ws As Worksheet

Dim LRow As Long, LCol As Long

Dim rng As Range


'~~> Change this with thee relevant sheet name

Set ws = ThisWorkbook.Sheets("Approved")


'~~> Get Last Row and Last Column

LRow = LastRow(ws)

LCol = LastColumn(ws)


With ws

'~~> Define your range

Set rng = .Range("A1:" & ReturnName(LCol) & LRow)


Debug.Print rng.Address

End With


ws.Range("L2").Select


ws.Range("rng").Sort Key1:=Range("L2"), Order1:=xlAscending, Header:=

xlGuess , OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _

DataOption1:=xlSortNormal

End Sub


'~~> Function to get last row

Public Function LastRow(Optional wks As Worksheet) As Long

If wks Is Nothing Then Set wks = ActiveSheet

LastRow = wks.Cells.Find(What:="*", _

After:=wks.Range("A1"), _

Lookat:=xlPart, _

LookIn:=xlFormulas, _

SearchOrder:=xlByRows, _

SearchDirection:=xlPrevious, _

MatchCase:=False).Row

End Function


'~~> Function to get last column

Public Function LastColumn(Optional wks As Worksheet) As Long

If wks Is Nothing Then Set wks = ActiveSheet

LastColumn = wks.Cells.Find(What:="*", _

After:=wks.Range("A1"), _

Lookat:=xlPart, _

LookIn:=xlFormulas, _

SearchOrder:=xlByColumns, _

SearchDirection:=xlPrevious, _

MatchCase:=False).Column

End Function


'~~> Function to get the Column name from Column Number

Function ReturnName(ByVal num As Integer) As String

ReturnName = Split(Cells(, num).Address, "$")(1)

End Function
 
I figured it out. I had already set my range, so no need to repeat it.


rng.Sort Key1:=Range("L2"), Order1:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _

DataOption1:=xlSortNormal


thanks
 
Back
Top