sort macro in Excel - excel

I am trying to use this code to sort a spreadsheet in excel but I am unsure how to put a predefined range in the .SetRange property. I wish to use the rng1Row variable I set above. Any help would be greatly appreciated.
N = Cells(Rows.Count, "A").End(xlUp).Row
Set rng1 = wb1.Sheets("SourceData").Cells.Range("A2:A" & N)
Set rng1Row = rng1.EntireRow
wb1.Worksheets("SourceData").Sort.SortFields.Clear
wb1.Worksheets("SourceData").Sort.SortFields.Add Key:=wb1.Sheets("SourceData").Cells.Range("A2:A" & N), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With wb1.Worksheets("SourceData").Sort
.SetRange
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With

Here is the documentation: expression .SetRange(Rng)
SetRange Range(rng1Row) (assuming rng1Row is a range)
However, let's look at the first part of your code -
N = Cells(Rows.Count, "A").End(xlUp).Row
Set rng1 = wb1.Sheets("SourceData").Cells.Range("A2:A" & N)
Set rng1Row = rng1.EntireRow
You are trying to get the row of a column. rng1Row = (Range("A:A").EntireRow). This is not a valid use of the property.

Related

VBA Excel sort the data from A to Z in one column with all data table changes

It might be such a duplicate question with:
VBA Sort A-Z on One Column
However I want to have the stuff clarified.
I tried to use this code for my purpose:
Sub SortAsc2()
Dim LastRow As Long
LastRow = Cells(Rows.Count, "M").End(xlUp).Row
'Columns("D:D").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("D"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("D2:D" & LastRow)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
where I got an error:
1004 Method 'Range' of object_Global failed
I tried another code then
Sub SortDataWithoutHeader()
Range("D1:D12").Sort Key1:=Range("D1"), Order1:=xlAscending, Header:=xlNo
End Sub
But the sort happens only within the column, whereas the other data is unaffected.
I want to have values from other cells corresponding to the data sort.
Is anyone able to help?
Give this a try.
Read code's comments and adjust it to fit your needs
Code:
Public Sub SortAsc2()
Dim targetSheet As Worksheet
Dim targetRange As Range
Dim lastRow As Long
' Set a reference to the sheet
Set targetSheet = ThisWorkbook.Worksheets("Sheet1")
' Find the last non empty row (based on column A)
lastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row
' Set the range to be sorted (A2= begins in row 2 and ends in column K?)
Set targetRange = targetSheet.Range("A2:K" & lastRow)
' Clear current sorting fields
targetSheet.Sort.SortFields.Clear
' You are missing a 1 after "D" in Range in your code
targetSheet.Sort.SortFields.Add Key:=Range("D1"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
With targetSheet.Sort
.SetRange targetRange
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Let me know if it works

VBA sort row by dates

I have a file containing dates on the first row, and a column of identifiers defining a table where I fill in the employee data for the corresponding data (See picture)
I want the dates to be sorted in the chronological order, but I only want to sort the dates, before I fill in the table.
I tried the following code
Sub sortByDates()
Dim sumSheet as Worksheet
Dim toSort as Range
Set sumSheet = ThisWorkbook.ActiveSheet
LastCol = sumsheet.Cells.Find(What:="*", After:=[a1], _
SearchOrder:=xlByColumns,
SearchDirection:=xlPrevious).Column
Set toSort = sumsheet.Rows(1).Resize(1, LastCol - 1).Offset(0, 1)
toSort.Select
ActiveWorkbook.Worksheets("Employees").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Employees").Sort.SortFields.Add Key:=toSort, SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Employees").Sort
.SetRange toSort
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
End Sub
However the dates moves but don't order as I wish. I think this might have to do with the fact that Excel Sort doesn't know how to handle the dates format, but not sure.
You should define the format of the data to be sorted. After this line in your code, toSort.Select, add this command:
Selection.NumberFormat = "[$-409]d-mmm-yy;#"
(change the format with appropriate one you use)
Here is the code I used and tested: I got the columns sorted correctly
(change feuil1 to your sheet name)
Sub sortByDates()
Dim sumSheet As Range
Dim toSort As Range
'Set sumSheet =
LastCol = ThisWorkbook.ActiveSheet.Cells.Find(What:="*", After:=[a1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set toSort = ThisWorkbook.ActiveSheet.Rows(1).Resize(1, LastCol - 1).Offset(0, 1)
toSort.Select
Selection.NumberFormat = "[$-409]d-mmm-yy;#"
ActiveWorkbook.Worksheets("feuil1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("feuil1").Sort.SortFields.Add Key:=toSort, SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("feuil1").Sort
.SetRange toSort
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
End Sub

Sort a column in descending order with unknown number of cells

I am trying to sort column A in descending order with unknown number of cells.
Getting run-time error - Method 'Sort' of object'_Worksheet' failed.
This code was working until recently when I got a new laptop with a different version of Excel.
lastrow = Cells(Rows.Count, 1).End(xlUp).Row
Range("A1").Select
ActiveWorkbook.Worksheets("New Working").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("New Working").Sort.SortFields.Add Key:=Range("A1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("New Working").Sort
.SetRange Range("A2:AT" & lastrow)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
The issue might come from the fact that you aren't fully qualifying your Worksheet when getting the value for the Last Row, so Excel would be looking at the ActiveSheet rather than the one you are wanting, I would suggest using something like the code below, where it is fully qualified:
Sub foo()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("New Working")
lastrow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=ws.Range("A1"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ws.Sort
.SetRange ws.Range("A1:AT" & lastrow)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub

Sort Entire Worksheet down to the last row

i have a macro that sorts all my data based on a custom sort but i want to use it on different worksheets that has different last row "number" if so to speak and i have this code here but i keep getting an error:
and just so that u know i am sorting column O
Sub SortDays()
' SortDays Macro
lRow = Worksheets("Banner Summary").Cells(Rows.Count, "B").End(xlUp).Row
Range("B1").Select
Range("A1:A" & lRow).Select
Range("O2").Activate
ActiveWorkbook.Worksheets("Banner Summary").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Banner Summary").Sort.SortFields.Add Key:=Range( _
"O2:O" & lRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
"M,T,W,R,F", DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Banner Summary").Sort
.SetRange Range("A1:A" & lRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
The error is: "The sort reference is not valid. Make sure that...."
it is quite long so any help would be really appreciated, and thnx in advance ^_^
Pass in the worksheet you want to sort:
Sub SortDays(byRef ws)
' SortDays Macro
lRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
'Range("B1").Select
'Range("A1:A" & lRow).Select
'Range("O2").Activate
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=Range( _
"O2:O" & lRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
"M,T,W,R,F", DataOption:=xlSortNormal
With ws.Sort
.SetRange Range("A1:O" & lRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Then this will run on any worksheet you pass it (assuming you have defined ws as whichever worksheet you want to use anyway:
Dim ws As Worksheet : Set ws = Workbooks("excelfilename").Worksheets("WhateverSheet")
prior to calling the Sub with SortDays ws

Use variable as .setrange property

I am trying to use this code to sort a spreadsheet in excel but I am unsure how to put a predefined range in the .SetRange property. I wish to use the rng1Row variable I set above. Any help would be greatly appreciated.
N = Cells(Rows.Count, "A").End(xlUp).Row
Set rng1 = wb1.Sheets("SourceData").Cells.Range("A2:A" & N)
Set rng1Row = rng1.EntireRow
wb1.Worksheets("SourceData").Sort.SortFields.Clear
wb1.Worksheets("SourceData").Sort.SortFields.Add Key:=wb1.Sheets("SourceData").Cells.Range("A2:A" & N), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With wb1.Worksheets("SourceData").Sort
.SetRange
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
By using .SetRange rng1Row you are only sorting 1 row.
Change to:
.SetRange wb1.Sheets("Source Data").Range("A2").CurrentRegion
Or similar to select the entire table of values.

Resources