Trying to make a dynamic sort macro, works on first column, then I get an error when I try to run on new column (trying to sort each column A-Z without changing the order of the other columns).
Sub SortCell()
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = ActiveSheet
Set StartCell = ActiveCell
ActiveCell.Columns("A:A").EntireColumn.Select
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:= _
ActiveCell, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveSheet.Sort
.SetRange ActiveCell.Range(StartCell, sht.Cells(LastRow, LastColumn))
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
MsgBox "Action complete.", vbInformation
End Sub
You're trying to work with the Sort code version that recording uses. This is very verbose and 'remembers' parameter values from previous operations. There is a much more concise syntax available that is just as effective.
dim c as long
with activesheet
for c=1 to .cells(1, .columns.count).end(xltoleft).column
if .cells(.rows.count, c).end(xlup).row >1 then
with .columns(c).Cells
.Sort Key1:=.cells(1), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlNo
end with
end if
next c
end with
Related
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
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
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
I have a question on how to automatically sort information as it is being submitted into a table via a userform.
I have tried the following code, but get errors. Because I'm new to Excel coding, I just can't figure out how to make this work:
Dim LR As Integer
LR = Range("A1:E1").End(xlUp).Row
Application.EnableEvents = False
Range("A1:BB" & LR).Sort Key1:=Range("A1"), Order1:=xlDescending, _
Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
Application.EnableEvents = True
Header Image
UserForm Image
The userform itself works perfectly fine. I'd like to sort via descending order in the date column.
Qualify the exact sheet and range you want to work with.
Clear the sort each time and re-apply the sort.
Get the last used range of data before setting the sort range. (The way you set LR will always be the 1st row.)
Like this:
Application.EnableEvents = False
Dim ws As Worksheet
Set ws = Sheets("Sheet1") 'change as needed
With ws
Dim LR As Long, rng As Range
LR = .Range("A" & .Rows.Count).End(xlUp).Row
Set rng = .Range("A1:BB" & LR)
With ws.Sort
With .SortFields
.Clear
.Add Key:=ws.Range("A2:A" & LR), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
End With
.SetRange rng
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
Application.EnableEvents = True
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.