VBA for sorting data with range length that isn't fixed

feni1388

Board Regular
Joined
Feb 19, 2018
Messages
61
Office Version
  1. 2021
Platform
  1. Windows
Hello....

I have recorded a macro code as below.

Range("A5:B5").Select
Range(Selection, Selection.End(xlDown)).Offset(-1, 0).Select
ActiveWorkbook.Worksheets("Result").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Result").Sort.SortFields.Add2 Key:=Range("B6:B13"), _
SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Result").Sort
.SetRange Range("A5:B13")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With

The problem is the range is until B13. I want to make it the same as the range that I selected (not including the last row) as the first 2 lines above.
The reason is that the list might become more or less in the future. I can't include the last row because it contains subtotal.

Please advise how to change the code (the one that I put in bold letter)

Thank you in advance.
 

Excel Facts

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney
Try this :
VBA Code:
Sub v()
Dim rng As Range
Set rng = Range([A5:B5], [A6:B6].End(xlDown).Offset(-1, 0))
ActiveSheet.Sort.SortFields.Clear
rng.Sort Key1:=[B5], Order1:=xlDescending, Header:=xlYes
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,215,086
Messages
6,123,033
Members
449,092
Latest member
ikke

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top