Sort Method of Range class failed - excel

I am new to VBA and having a hard time figuring out this code.I am doing a course online and i followed the same steps but somehow i'm getting an error.I recently installed Excel 2013 and dont know if thats the issue.I tried putting .Range("A4") but that gives me an error of "Invalid or Unqualified Reference"
Sub DivisionSort()
'
' Sort List by Division Ascending
'
'
Selection.Sort Key1:=Range("A4"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End Sub
Sub CategorySort()
'
' Sort List by Category Ascending
'
'
Selection.Sort Key1:=Range("B4"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End Sub
Sub TotalSort()
'
' Sort List by Total Sales Ascending
'
'
Selection.Sort Key1:=Range("F4"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End Sub
Public Sub SortList()
Dim userinput As String
userinput = InputBox("1=Sort by Division, 2=Sort by Category,3=Sort by Total")
If userinput = "1" Then
DivisionSort
ElseIf userinput = "2" Then
CategorySort
ElseIf userinput = "3" Then
TotalSort
End If
End Sub

Try to avoid use of 'Selection'. Try instead a full reference:
ThisWorkbook.Sheets("Sheet1").Range("Table1").Sort

Related

Excel Multi-Level Auto Sorting

Been trying for days to figure out how to do a two-level auto sort in VBA. I've managed to get a single level auto-sort working, but when I try adding a second level it overrides the first level sorting I did previously. Data is kept in Rows.
Here is what I am trying to set up to autosort
This is the VBA i have written right now for the 1st level or sorting which Sorts the Active? Column
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Range("A:A")) Is Nothing Then
Range("A1").Sort key1:=Range("A2"), _
Order1:=xlDescending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
End If
End Sub
Here's the new formula I wrote thanks to your comments. Seems to work. My problem before was I kept doing Key2 and Order2 as a new If function instead of as part of the previous one.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A:A")) Is Nothing Then
Range("A1").Sort key1:=Range("A2"), _
Order1:=xlDescending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
key2:=Range("B2"), _
Order2:=xlAscending, Header:=xlYes, _
Orientation:=xlTopToBottom
End If
End Sub

RunTime Error 1004. Sort method of Range class failed

I have written a VBA macro which will sort rows based on user inputs. So if an user inputs 1, then the sorting will happen based on a certain condition, if 2 then an another condition and so on. However when I run the code I get the error "Run Time error 1004: Sort method of Range class failed". Can any of the VBA experts help how I can overcome this error. Below is the entire code block :
Public Sub Sortlist()
Dim userinput As String
Dim tryagain As Integer
userinput = InputBox("1 = Sort By Division,2 = Sort by Category, 3 = Sort by Total sales")
If userinput = "1" Then
DivisionSort
ElseIf userinput = "2" Then
CategorySort
ElseIf userinput = "3" Then
TotalSort
Else
tryagain = MsgBox("Incorrect Value.Try again?", vbYesNo)
If tryagain = 6 Then
Sortlist
End If
End If
End Sub
------------------------------------
Sub DivisionSort()
'
' Sort List by Division Ascending
'
'
Selection.Sort Key1:=Range("A4"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End Sub
----------------------------------------------
Sub CategorySort()
'
' Sort List by Category Ascending
'
'
Selection.Sort Key1:=Range("B4"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End Sub
--------------------------------
Sub TotalSort()
'
' Sort List by Total Sales Ascending
'
'
Selection.Sort Key1:=Range("F4"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End Sub
CurrentRegion Saves the Day
Your code was failing when your Selection was out of range. So I created a Sub with one argument called SortRange which uses CurrentRegion to always 'point' to the range.
Option Explicit
Public Sub Sortlist()
Dim userinput As String
Dim tryagain As Integer
userinput = InputBox("1 = Sort By Division,2 = Sort by Category, 3 = Sort by Total sales")
If userinput = "1" Then
DivisionSort
ElseIf userinput = "2" Then
CategorySort
ElseIf userinput = "3" Then
TotalSort
Else
tryagain = MsgBox("Incorrect Value.Try again?", vbYesNo)
If tryagain = 6 Then
Sortlist
End If
End If
End Sub
'------------------------------------
Sub SortRange(rng As Range)
rng.CurrentRegion.Sort Key1:=rng, Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End Sub
'------------------------------------
Sub DivisionSort()
'
' Sort List by Division Ascending
'
SortRange Range("A4")
End Sub
'----------------------------------------------
Sub CategorySort()
'
' Sort List by Category Ascending
'
SortRange Range("B4")
End Sub
'--------------------------------
Sub TotalSort()
'
' Sort List by Total Sales Ascending
'
SortRange Range("F4")
End Sub
I had the same issue when doing an online Excel VBA course. Likely the same course. The error was in the course supplied spreadsheet. I managed to troubleshoot the problem and it was relating to this issue found on the web.
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/block-if-without-end-if?
So a simpler fix but then my PC rebooted and I lost the macro that I edited and got to work.
I tried the VBasic2008 "Fix" and that works perfectly fine as well.
Just my comments on what I went thru, not trying to persuade or dissuade otherwise.
Barry

VBA, Sorting based on custom list

I am trying to sort my records based on Col A values, there are 5 different values and many rows (in a table). Also I have the custom list created in excels built in sort feature.
I am getting an error Sort method of range class failed on
oRangeSort.Sort Key1:=oRangeKey, Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _
Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
Here is my code:
Sub Sort()
Dim oWorksheet As Worksheet
Set oWorksheet = ActiveWorkbook.Worksheets("database")
Dim oRangeSort As Range
Dim oRangeKey As Range
' one range that includes all colums do sort
Set oRangeSort = oWorksheet.Range("A2:FR20000")
' start of column with keys to sort
Set oRangeKey = oWorksheet.Range("A2")
' custom sort order
Dim sCustomList(1 To 5) As String
sCustomList(1) = "sort1"
sCustomList(2) = "sort2"
sCustomList(3) = "sort3"
sCustomList(4) = "sort4"
sCustomList(5) = "sort5"
Application.AddCustomList ListArray:=sCustomList
oWorksheet.Sort.SortFields.Clear
oRangeSort.Sort Key1:=oRangeKey, Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _
Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
' clean up
ActiveSheet.Sort.SortFields.Clear
Application.DeleteCustomList Application.CustomListCount
Set oWorksheet = Nothing
End Sub
Try a VBA sort as opposed to rewriting the recorded sort code.
Sub custom_sort()
Dim vCustom_Sort As Variant, rr As Long
vCustom_Sort = Array("sort1", "sort2", "sort3", "sort4", "sort5")
Application.AddCustomList ListArray:=vCustom_Sort
With ActiveWorkbook.Worksheets("database")
.Sort.SortFields.Clear
rr = .Cells(.Rows.Count, "A").End(xlUp).Row
With .Range("A2:FR" & rr)
.Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, DataOption1:=xlSortNormal, _
Orientation:=xlTopToBottom, Header:=xlYes, MatchCase:=False, _
OrderCustom:=Application.CustomListCount + 1
End With
.Sort.SortFields.Clear
End With
End Sub

Want to augment code to paste only values, would like to change range to specific columns

Looking to augment my existing code to paste only values, and would like to change the copy range to select columns only.
Sub CopySort()
Dim dEnd As Integer
Sheets("Sorted").Range("A2:R250").ClearContents
Sheets("Portfolio").Select
Range("a1").Select
dEnd = Selection.End(xlDown).Row
Range("A5:" & "Z" & dEnd).Copy
Sheets("Sorted").Select
Range("A2").Select
ActiveSheet.Paste
Columns("A:R").Sort key1:=Range("A:A"), order1:=xlAscending, Header:=xlYes, _
key2:=Range("F:F"), order2:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
Application.CutCopyMode = False
End Sub

Operation of filters in VBA

I have very recently started writing in VBA having written in various other languages over the years. I am currently having some strange issues using filters in Excel VBA and wondered if anyone could shed any light on the behaviour I am experiencing.
I would like to filter by dataset by a number of different columns, one at a time, I am doing this by copying my data set to a new sheet and sorting the data there. For the first filter I am using:
Sheets("Temp Data").Range("A:T").ClearContents
Sheets("Main Sheet").Range("A1", "T" & CountLV_Rows).Copy Sheets("Temp Data").Range("A1", "T" & CountLV_Rows)
Sheets("Temp Data").Range("A1", "T" & CountLV_Rows).Sort Key1:=Range("R1"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
This works successfully. I would now like to filter by the values in Col C INSTEAD, I repeat the above code (including the clearcontents command as I thought that would improve my chances of success... and just swap the Key1 value to C1
For second (hopefully new filter), I used:
`Sheets("Temp Data").Range("A:T").ClearContents
Sheets("Main Sheet").Range("A1", "T" & CountLV_Rows).Copy Sheets("Temp Data").Range("A1", "T" & CountLV_Rows)
'Sort the data so ascending site numbers in column C
Sheets("Temp Data").Range("A1", "T" & CountLV_Rows).Sort Key1:=Range("C1"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal`
However, my data is sorted by column C after it is first sorted by column R...
How can I wipe any previous sorts applied?
Thanks for your help
I think it might have to do with the fact that you aren't qualifying your worksheets and ranges, i.e., explicitly specifying which workbook or worksheet they are in. That's something you always want to do.
I've done that below and it works for me in Excel 2010:
Sub test()
Dim CountLV_Rows As Long
Dim wbActive As Excel.Workbook
Set wbActive = ActiveWorkbook
With wbActive
.Sheets("Temp Data").Range("A:T").ClearContents
CountLV_Rows = .Sheets("Main Sheet").Range("A" & Rows.Count).End(xlUp).Row
.Sheets("Main Sheet").Range("A1", "T" & CountLV_Rows).Copy _
Destination:=.Sheets("Temp Data").Range("A1", "T" & CountLV_Rows)
With .Sheets("Temp Data")
.Range("A1", "T" & CountLV_Rows).Sort Key1:=.Range("R1"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
.Activate
MsgBox "Sorted by R"
.Range("A1", "T" & CountLV_Rows).Sort Key1:=.Range("C1"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End With
End With
End Sub

Resources