How to Autosort a Userform Entry - excel

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

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

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 VBA CustomSort from Range

Sub RRC()
Dim noOfLists As String
With Sheets("All_list")
Application.CutCopyMode = False
Application.AddCustomList ListArray:=Range("AU2:AU4")
noOfLists = Application.CustomListCount
noOfLists = noOfLists + 1
End With
ActiveWorkbook.Worksheets("All_list").ListObjects("All").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("All_list").ListObjects("All").Sort.SortFields.Add2 _
Key:=Range("All[RRC]"), SortOn:=xlSortOnValues, Order:=xlAscending, _
CustomOrder:=CVar(noOfLists), DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("All_list").ListObjects("All").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Application.DeleteCustomList (noOfLists - 1)
End Sub
Could anyone Help to figure out why this does not work, it runs, but does not sort.
Range AU2:AU4 will be dynamic, meaning that sorting there will always be different, therefore the key moment here is to use the latest sort in that range when applying VBA
Thank you
This is what I would have used. Let me know if there's a reason you're using the CustomOrder in the actual sort
Sub RRC()
Dim currWorksheet As Worksheet
Set currWorksheet = ActiveWorkbook.Worksheets("All_list")
Dim newRangeSort As Range
Dim newRangeKey As Range
' Fields to be sorted
Set newRangeSort = currWorksheet.Range("AU2:AU4")
' "Header" column of which to sort from
Set newRangeKey = currWorksheet.Range("AU1")
'Your sort
Dim customSort As String
customSort = ("test")
'Actual sort
currWorksheet.Sort.SortFields.Clear
newRangeSort.Sort Key1:=newRangeKey, Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _
Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
' clean up
Set currWorksheet = Nothing
End Sub
There should be no reason to use a With here. This is a much better way of pulling a custom sort, as using vba - Application.AddCustomList is just an awful way to do things - very unfriendly
Here is what i did, after some intzernet research:
Sub Segment()
Dim x() As Variant
With Sheets("All_list")
.Range("AP2:AP10").Clear
.Range("AO2:AO10" & .Cells(.Rows.Count, "AO").End(xlUp).Row).Copy
.Range("AP2").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
x = Application.Transpose(Sheets("All_list").Range("AP2:AP10").Value)
ActiveWorkbook.Worksheets("All_list").ListObjects("All").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("All_list").ListObjects("All").Sort.SortFields.Add2 _
Key:=Range("All[Segment]"), SortOn:=xlSortOnValues, Order:=xlAscending, _
CustomOrder:=Join(x, ","), DataOption:=xlSortNormal
End With
With ActiveWorkbook.Worksheets("All_list").ListObjects("All").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
First ranges just copy paste code cells into text, otherwise macro doe not run, join allowed to skip creation of custom list in excel

Issues in VBA ".Apply"

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

Column Sort not sorting referenced column, only on active column

I am trying to adapt some code that copies and pastes two separate ranges into another on a different sheet and then sorts it alphabetically. Problem is when i hide the sheet - even though I unhide and re-hide it to run the Macro - it seems to sort only on the Active Column.
I have singled out in bold the sorting code in the second macro below. The GetNamesList macro calls the ConsolidateList towards the end of its code.
The GetNamesList is set to run on workbook open:
Private Sub Workbook_Open()
GetNamesList
End Sub
The original code for GetNamesList is from: http://bit.ly/1y3dU6n by #Siddharth-rout
Sub GetNamesList()
Dim rng As Range, aCell As Range
Dim MyAr() As Variant
Dim n As Long, i As Long
Application.ScreenUpdating = False
Sheet28.Visible = True
'~~> Change this to the relevant sheet
With Sheet3
'~~> Non Contiguous range
Set rng = .Range("Table2[Contact 1],Table2[Contact 2]")
'~~> Get the count of cells in that range
n = rng.Cells.Count
'~~> Resize the array to hold the data
ReDim MyAr(1 To n)
n = 1
'~~> Store the values from that range into
'~~> the array
For Each aCell In rng.Cells
MyAr(n) = aCell.Value
n = n + 1
Next aCell
End With
'~~> Output the data in Sheet
'~~> Vertically Output to sheet 28
Sheet28.Cells(1, 1).Resize(UBound(MyAr), 1).Value = _
Application.WorksheetFunction.Transpose(MyAr)
ConsolidateList
Sheet28.Visible = False
Application.ScreenUpdating = True
End Sub
ConsolidateList is:
Sub ConsolidateList()
'
' ConsolidateList Macro
' Remove duplicates and blanks
'
With Sheet28.Range("A1:A1000")
.Value = .Value
.RemoveDuplicates Columns:=1, Header:=xlNo
On Error Resume Next
.SpecialCells(xlCellTypeBlanks).Delete xlShiftUp
On Error GoTo 0
End With
Columns("A:A").Sort Key1:=Range("A1"), Order1:=xlAscending
End Sub
Thanks for your help...
**Update - recording of macro to do the same thing...
Sub TestSort()
'
' TestSort Macro
'
Sheets("Jan").Select
Sheets("Sheet1").Visible = True
ActiveWindow.SmallScroll Down:=-405
Range("A1:A134").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:A134")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWindow.SmallScroll Down:=-245
Sheets("Sheet1").Select
ActiveWindow.SelectedSheets.Visible = False
End Sub
Thanks #S-O. By taking your suggestion and puzzling over the recorded code I was able to cobble together the following:
Sub ConsolidateList()
'
' ConsolidateList Macro
' Remove duplicates and blanks
'
With Sheet28.Range("A1:A1000")
.Value = .Value
.RemoveDuplicates Columns:=1, Header:=xlNo
On Error Resume Next
.SpecialCells(xlCellTypeBlanks).Delete xlShiftUp
On Error GoTo 0
End With
Sheet28.Sort.SortFields.Clear
Sheet28.Sort.SortFields.Add Key:=Range("A1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:A134")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Though an ActiveWorkbook seems to have snuck in there...!
**UPDATE
Replaced
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:A134")
With:
At top
Dim Lastrow As Integer
Then
Lastrow = Sheet28.Cells.Find("*", searchorder:=xlByRows,searchdirection:=xlPrevious).Row
With Sheet28.Sort
.SetRange Range("A1:A" & Lastrow)
That fixed it...

Resources