Set range in VBA sort - vba

I am trying to sort data in Excel VBA. My sheet could have a variable amount of data so I am using the Range.End method to find the last row/ column of the sheet. Though, when I try to set the range for the sort it gives me an Object Required error and I am not sure why. I have pasted my code below. Any help would be greatly appreciated.
With Sheet9.Sort
.SetRange (Sheet9.Range("A1").CurrentRegion)
.SortFields.Clear
.SortFields.Add Key:=rng2, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With

EDITED BASED ON COMMENTS:
I entered the below code into a mock spreadsheet that I created and it seems to work fine. The error described in the comments: Sort Reference is not valid indicates that there's possibly an issue in defining the key. Try to use my code (replace with necessary information) and let me know if it works.
Sub Doit()
Set rng2 = Sheet1.Range("A1:A5")
With Sheet1.Sort
.SortFields.Clear
.SortFields.Add Key:=rng2, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange Sheet1.Range("A1").CurrentRegion
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Based on the ability to use .End for both rows and columns, I assume you have a contiguous data set. If so, instead of complicating matters, simply use:
Range("A1").CurrentRegion to set your range object.
This recognizes the entire dataset that is built around Range("A1")

Related

Why isn't my VBA sorting my column data correctly?

I am trying to delete the first row of the Excel sheet and sort a specific column using its name "CUST_RELPO". I am using the column header name since the name may change.
Sorting and copying the column from the second row since I do need to copy the column header.
Sub ClearFirstRow()
'
' ClearFirstRow Macro
'
'
Rows("1:1").Select
Selection.Delete Shift:=xlUp
Cells.Select
Dim rngcustrelpo As Range
xindex = Application.ActiveCell.Column
Set rngcustrelpo = ActiveSheet.UsedRange.Find("CUST_RELPO")
If rngcustrelpo Is Nothing Then
MsgBox "CUST_RELPO column was not found."
Exit Sub
End If
'Cells.Select
Range(rngcustrelpo, rngcustrelpo.End(xlDown)).Select
ActiveWorkbook.Worksheets("BACKORDER").Sort.SortFields.Add Key:=ActiveSheet.UsedRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("BACKORDER").Sort
.SetRange ActiveSheet.UsedRange
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Set rngcustrelpo1 = rngcustrelpo.Offset(1, 0)
Range(rngcustrelpo1, rngcustrelpo1.End(xlDown)).Select
Selection.Copy
End Sub
However, it is not sorting the data like I am expecting. I am not sure what I am missing here.
Key:=ActiveSheet.UsedRange is a complete misunderstanding of the sort method. (Usedrange covers the whole used area on the sheet - often "empty" cells, too.) The same applies to .SetRange ActiveSheet.UsedRange. It is not bad just needless. SetRange is needed when you want to limit the area to be sorted. If you want to sort on only one key (column), then change this
ActiveWorkbook.Worksheets("BACKORDER").Sort.SortFields.Add Key:=ActiveSheet.UsedRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("BACKORDER").Sort
.SetRange ActiveSheet.UsedRange
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
to this:
With ActiveWorkbook.Worksheets("BACKORDER").Sort
.Key rngcustrelpo
.Header = xlYes
.MatchCase = False
.Order:=xlAscending
.Orientation = xlTopToBottom
.SortOn:=xlSortOnValues
.DataOption:= xlSortTextAsNumbers
.SortMethod = xlPinYin
.Apply
End With
And you can find more info here: Excel SortFields add then sort and here: Most efficient way to sort and sort syntax VBA

Unable to get the Sort property of the Range class

I'm getting the above error when performing a sort. I've fully qualified all objects and checked that my variables hold the correct values. The error occurs on the first line:
With ws.Columns("A:E").Sort
.SortFields.Clear
.SortFields.Add Key:=ws.Range("A2:A" & oldLastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange ws.Range("A1:E" & oldLastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
It doesn't seem to matter how I refer to the range, each of these gives the same error:
With ws.Range("A:E").Sort
With ws.Range("A1:E" & oldLastRow).Sort
There is data in each cell of the range and the columns have headers. What could be causing this problem?
ws.Columns("A:E").Sort is calling the Sort function of a Range which is different from the Sort class of the worksheet:
(hit F2 in the VBA editor to get to that screen)
So your code will likely work if you just remove the .Columns("A:E") of your snippet e.g.:
With ws.Sort
.SortFields.Clear
.SortFields.Add Key:=ws.Range("A2:A" & oldLastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange ws.Range("A1:E" & oldLastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
You are already saying what you want to sort with .SetRange ws.Range("A1:E" & oldLastRow) so you can see it is a bit redundant to also have it in the With statement (as well as generating the error).
PS I get
Run-time error '438': Object doesn't support this property or method

Sort By Column A Not Working Excel VBA

I'm trying to sort by column A from range A2-A30000 and I want to make the drop down on Column A Row 1 but it is neither sorting or enabling the dropdown on Column A Row 1. Even without VBA when I just select the A1 and press filter it automatically ends up putting the dropdown on A2. Another problem that occurs is that it only sorts column A but just moves column A around but leaves the other columns alone making the entire worksheet wrong.
ActiveWorkbook.Worksheets("Sheet3").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet3").Sort.SortFields.Add Key:=Range("A2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A2:A30000")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Any idea what might be wrong?
ActiveWorkbook.Worksheets("Sheet3").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet3").Sort.SortFields.Add Key:=Range("A2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet3").Sort
.SetRange Range("A2:BZ30000")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Thanks for the comment
You are only referencing column A; use the .CurrentRegion property to isolate the data 'island' radiating out to the first completely blank row and completely blank column. I suspect you have a text column label in A1.
With ActiveWorkbook.Worksheets("Sheet3")
With .Cells(1, "A").CurrentRegion
.Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
End With
End With
The recorded code works fine in some instances but sorting can be handled by VBA functionality more efficiently.
You really should know whether you have a header or not; never use xlGuess.

sort rows in excel programmatically

I am fairly new in generating excel reports using vb.net. My problem is I can't seem to properly sort the rows.
What I want to do is sort all the rows including the client name using the total value as the reference. I use interop assembly and this is the code that I've tried but it does not even work properly.
Dim myRange As Excel.Range
myRange = Wsheet.Range("A7:AG17")
myRange.Select()
myRange.Sort(Key1:=myRange.Range("AG7:AG17"), _
Order1:=Excel.XlSortOrder.xlDescending, _
Orientation:=Excel.XlSortOrientation.xlSortRows, _
SortMethod:=Excel.XlSortMethod.xlPinYin, _
DataOption1:=Excel.XlSortDataOption.xlSortNormal)
This doesn't use your ranges, but to sort your data by the totals have you tried recording a macro whilst doing it manually first?
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("AG8:AG16" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A7:AG16")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With

Select ActiveCell in another sheet

I am working on a project that will sort all the cells in another worksheet based on criteria. I need to activate a cell in another worksheet to make it work. I tried finding a solution but no luck.
I recorded a macro from my workbook and tweaked it a bit so it would fit my need. When I run the code, Runtime Error 1004 appears.
I need a code to replace
SetRange ActiveCell.Offset(-1, 0).Range("A1:AF30436")
Any suggestion will be appreciated.
Here's the code:
Sheets("Source").Select
ActiveWorkbook.Worksheets("Source").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Source").Sort.SortFields.Add Key:=ActiveCell.Range _
("A1:A30435"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Source").Sort
.SetRange ActiveCell.Offset(-1, 0).Range("A1:AF30436")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
when you record macro, you click on the cell in the second sheet and start the sort routine. Macro correctly recorded this.
however when you are doing this in VBA, the "active cell" could be anything and in most cases you dont need this as long as you know the datarange that you need to work with
dim ws as WorkSheet
set ws = Sheets("Source")
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=ws.Range _
("A1:A30435"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ws.Sort
.SetRange Range("A1:AF30436") ' Change here to itended dataset
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With