A more flexible sort - excel

I created a macro to sort a list of customer names and it works however as you can see below it sorts the list that now goes from A2 through A47. I'm worried that when the size of the list grows or contracts my macro will not work properly. How can I adjust this so that my sort macro works in any list running down column A. Thank you.
Sub ByCustomerName()
'
' ByCustomerName Macro
' Sorts by Customer Name
'
'
ActiveWorkbook.Worksheets("My Customers").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("My Customers").Sort.SortFields.Add Key:=Range( _
"A2:A47"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("My Customers").Sort
.SetRange Range("A1:B47")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub

You just need to set your range rather than hard-coding it\
Change .SetRange Range("A1:B47")
At the top of the code try
Dim sortRange As Range
Dim lastRow As Long
Dim ws As Worksheet
Set ws = Sheet1
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Set sortRange = Range("A1:B" & lastRow)
Then .SetRange sortRange

Try Range("A1", Range("A1").End(xlDown))
This should select all non-empty rows starting with A1.

Related

Data in excel not sorting

I am trying to sort the data in my excel but it is not getting sorted.I have used the below code in VBA
Set total_data = Worksheets("CREATE_INFOSOURCES").Range("A5", Range("A5").End(xlToRight))
Set sorting_column = Worksheets("CREATE_INFOSOURCES").Range("A5", Range("A5").End(xlDown))
total_data.Sort Key1:=sorting_column, Order1:=xlAscending, Header:=xlYes
I want to sort the data in ascending order based on column A and my data is filled from A5 row.
Please tell where I am doing wrong.
See if this works for you.
Public Function sort()
Dim ws As Worksheet
Dim RangeSort As Range
Dim RangeKey As Range
Set ws = Worksheets("CREATE_INFOSOURCES")
Lrow = ws.Range("A" & Rows.Count).End(xlUp).Row
'one range that includes all columns do sort
Set RangeSort = ws.Range("A5:A" & Lrow)
With ws
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=RangeKey, _
Order:=xlAscending, _
DataOption:=xlSortNormal
End With
With ws.Sort
.SetRange RangeSort
.Orientation = xlTopToBottom
.Header = xlYes
.MatchCase = False
.Apply
End With
'clean up
ActiveSheet.Sort.SortFields.Clear
Set ws = Nothing
End Function

How do I adjust this code which sorts a single sheet so that it sorts multiple sheets in a workbook

I'm running a macro which takes data from one sheet and copies into several other worksheets. I want to adjust the following code so that I can sort ALL worksheets in my workbook by Column Q once it's been copied and not just the sheet named "Sorted1"
ActiveWorkbook.Worksheets("Sorted1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sorted1").Sort.SortFields.Add2 Key:=range("D2:D" & lastrow _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sorted1").Sort
.SetRange range("A1:Q" & lastrow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
You can call sheets not only by their name, but also by their position in your workbook.
sheets("sheet1") <- calls sheet named "sheet1"
sheets(1) <- calls the first sheet
If you want your script to iterate through all sheets, you can use a for-loop and replace the sheet-name by the iterative variable.
for i = 1 to x 'replace x with number of sheets
ActiveWorkbook.Worksheets(i).sort (your script)...
....
Next
If the number of sheets changes sometimes, use the following command instead of x to count the number of sheets
Application.Sheets.Count
So:
for i = 1 to Application.Sheets.Count
ActiveWorkbook.Worksheets(i).sort (your script)...
....
Next
Try the next code, please:
Sub sortAllSheets()
Dim sh As Worksheet, wb As Workbook, LastRow As Long
Set wb = ActiveWorkbook
For Each sh In wb.Worksheets
'if all the columns have the same number of rows, this can be done for all the code
LastRow = sh.Range("D" & Rows.Count).End(xlUp).row
sh.Sort.SortFields.Clear
sh.Sort.SortFields.Add2 key:=sh.Range("D2:D" & LastRow) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With sh.Sort
.SetRange sh.Range("A1:Q" & LastRow) 'if LastRow is the same as in D:D
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next
End Sub

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

Excel Macro: Apply sorting to each sheet

Here is the code that I am using to apply sorting to each page except two. The system is throwing following error.
"select method of range class failed".
Private Sub CommandButton3_Click()
Dim ws1 As Worksheet
For Each ws1 In Worksheets
If ws1.Name <> "Sheet1" And ws1.Name <> "Extra" Then
**ws1.Range("A1:V1000").Select** Something is wrong here I suspect
ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Clear
ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Add Key:=Range("I2:I1000") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Add Key:=Range("T2:T1000") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(ws1).Sort
.SetRange Range("A1:V1000")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End If
Next ws1
End Sub
Please help.
I would Select the worksheet before Selecting the range. Replace:
ws1.Range("A1:V1000").Select
with:
ws1.Select
Range("A1:V1000").Select
You may not need these Selections if you use .Range() rather than Range() in the code that follows. Also since ws1 is a worksheet object,:
ActiveWorkbook.Worksheets(ws1)
should be replace with:
ActiveWorkbook.Worksheets(ws1.Name)
There may be other problems with code.

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

Resources