Cleaning up code in recorded Excel Macro - excel

I used the Record Macro function to create this, but it runs real slow and I want to see if anyone had any ideas on how to clean it up. It looks as if I have two sorts here doing the same thing? Thanks in advance.
Sub Activations()
'
' Master_Button2_2_Click Macro
'
'
Application.ScreenUpdating = False
Sheets("Index").Select
Columns("A:C").Select
ActiveWorkbook.Worksheets("Index").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Index").Sort.SortFields.Add Key:=Range("B2:B12000" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Index").Sort
.SetRange Range("A1:C12000")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Sheets("Duplicates").Select
ActiveSheet.Range("$L$4:$N$3476").AutoFilter Field:=1, Criteria1:= _
"Activate"
Sheets("Master").Select
ActiveSheet.Range("$A$2:$BU$11965").AutoFilter Field:=73, Criteria1:= _
"A"
Application.ScreenUpdating = True
End Sub

Your code is fairly straightforward although it isn't entirely clear what it is trying to accomplish. Here is a quick rewrite putting several With ... End With statement to use to narrow down the affected work areas.
Sub Activations()
' Master_Button2_2_Click Macro
Dim lr As Long
appTGGL bTGGL:=False
With Worksheets("Index")
lr = .Cells.SpecialCells(xlCellTypeLastCell).Row
With .Range("A1:C" & lr)
.Cells.Sort Key1:=.Columns(2), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
End With
End With
With Worksheets("Duplicates")
If .AutoFilterMode Then .AutoFilterMode = False
lr = .Cells.SpecialCells(xlCellTypeLastCell).Row
With .Range("L4:N" & lr)
.AutoFilter Field:=1, Criteria1:="activate"
End With
End With
With Worksheets("Master")
If .AutoFilterMode Then .AutoFilterMode = False
lr = .Cells.SpecialCells(xlCellTypeLastCell).Row
With .Range("A2:BU" & lr)
.AutoFilter Field:=73, Criteria1:="A"
End With
.Select
End With
appTGGL
End Sub
Sub appTGGL(Optional bTGGL As Boolean = True)
With Application
.EnableEvents = bTGGL
.ScreenUpdating = bTGGL
.DisplayAlerts = bTGGL
.Calculation = IIf(bTGGL, xlCalculationAutomatic, xlCalculationManual)
End With
End Sub
Sample data and a short narrative of explanation would have helped this question. We don't all speak english but we all speak code and data.

Related

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

VBA for sorting in excel in addition to current code to run for any worksheet

I'm trying to add this VBA from a list of other commands however I'm getting an error. Please assist with the correct syntax for sort. thank you.
error message is: run-time error '1004' application-defined or object-defined error.
Sub filter()
Dim N As Long
Dim wsName As String
For N = 1 To ThisWorkbook.Sheets.Count
wsName = ThisWorkbook.Worksheets(N).Name
If Len(wsName) = 3 Then
Sheets(wsName).Range("$A$1:$XFC$1104").AutoFilter Field:=12, Criteria1:=">=365" _
, Operator:=xlAnd
Sheets(wsName).Range("$A$1:$XFC$1104").AutoFilter Field:=17, Criteria1:=">100" _
, Operator:=xlAnd
Sheets(wsName).Range("$A$1:$XFC$7606").AutoFilter Field:=20, SortOn:=xlSortOnValues, Order:=xlDescending _
, Operator:=xlAnd
With ActiveWorkbook.Worksheets("i_ULO").AutoFilter.sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Else
end if
next n
end sub
After adding this code below. New error came up.
Dim N As Long
Dim wsName As String
For N = 1 To ThisWorkbook.Sheets.Count
wsName = ThisWorkbook.Worksheets(N).Name
If Len(wsName) = 3 Then
With .Cells(1, "A").CurrentRegion
.Cells.sort Key1:=.Columns(20), Order1:=xlDescending, _
Orientation:=xlTopToBottom, Header:=xlYes
End With
End With
Compile Error
reference
Try this instead:
Sub filter()
Dim N As Long
Dim wsName As String
For N = 1 To ThisWorkbook.Sheets.Count
wsName = ThisWorkbook.Worksheets(N).Name
If Len(wsName) = 3 Then
Sheets(wsName).Range("$A$1:$XFC$1104").AutoFilter Field:=12, Criteria1:=">=365" _
, Operator:=xlAnd
Sheets(wsName).Range("$A$1:$XFC$1104").AutoFilter Field:=17, Criteria1:=">100" _
, Operator:=xlAnd
Sheets(wsName).AutoFilter.Sort.SortFields.Add Key:=Range("T1:T7606"), SortOn:=xlSortOnValues, Order:=xlDescending
With ActiveWorkbook.Worksheets("i_ULO").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End If
Next N
End Sub
You can use this VBA Sort code to sort the active worksheet's data table radiating out from A1 with column T as the primary sort key.
Dim N As Long
Dim wsName As String
For N = 1 To ThisWorkbook.Sheets.Count
wsName = ThisWorkbook.Worksheets(N).Name
If Len(wsName) = 3 Then
with ThisWorkbook.Worksheets(N)
with .cells(1, "A").currentregion
.Cells.Sort Key1:=.Columns(20), Order1:=xldescending, _
Orientation:=xlTopToBottom, Header:=xlyes
end with
end with
end if
next n

Optimize slow VBA code

I have the following code - most of which was recorded with the macro recorder. It is slow and seems to be kind of unreliable (sometimes it takes about 1 minute and other times it takes much longer).
I am wondering if anyone here can help me clean this up and get it to run more efficiently.
Thanks!
Sub RemainingMIUL()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Sheets("Sheet2").Select
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Sheets("Sheet1").Select
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Add Key:=Range _
("L1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("L:L").Select
Selection.Copy
Sheets("Sheet2").Select
Range("A1").Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Application.CutCopyMode = False
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Add Key:=Range _
("A1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Sheets("Sheet2").Select
Range("B2").Select
Dim cell As Range
For Each cell In Range("B2", Cells(Rows.Count, "B").End(xlUp))
If Range("A:A").Find(What:=cell.Value2, LookAt:=xlWhole) Is Nothing Then cell.Interior.Color = vbYellow
Next cell
With Sheets("Sheet2")
For Each cell In .Range("B2", Cells(Rows.Count, "B").End(xlUp))
If .Range("A:A").Find(What:=cell.Value2, LookAt:=xlWhole) Is Nothing Then _
Intersect(.UsedRange, cell.EntireRow).Offset(, 1).Copy _
Sheets("Sheet1").Cells(Rows.Count, "L").End(xlUp).Offset(1)
Next cell
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
Try combining the 2 for loops that you have at the bottom of the code. They both loop through the column B and run code when the same criteria is met.
With Sheets("Sheet2")
For Each cell In .Range("B2", Cells(Rows.Count, "B").End(xlUp))
If .Range("A:A").Find(What:=cell.Value2, LookAt:=xlWhole) Is Nothing Then
Intersect(.UsedRange, cell.EntireRow).Offset(, 1).Copy Sheets("Sheet1").Cells(Rows.Count, "L").End(xlUp).Offset(1)
cell.Interior.Color = vbYellow
End if
Next cell
End With
You can then delete the first loop
For Each cell In Range("B2", Cells(Rows.Count, "B").End(xlUp))
If Range("A:A").Find(What:=cell.Value2, LookAt:=xlWhole) Is Nothing Then cell.Interior.Color = vbYellow
Next cell

How to Autosort a Userform Entry

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

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