Hey guys i Keep getting a run time error 1004 Method 'Range' of object' _Global' Failed when i try to do this simple sort.
Sub Assy_Weld_TrumpfSort()
'
' Assy_Weld_TrumpfSort
'
Dim sh As Worksheet
Dim TableName As String
Dim theTable As ListObject
Set sh = ActiveSheet
TableName = sh.Name
Set theTable = ActiveWorkbook.Worksheets(TableName).ListObjects(TableName)
theTable.sort.SortFields.Clear
theTable.sort.SortFields.Add _
Key:=Range(TableName & "[PART NUMBER]"), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
With theTable.sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
You will be getting that error because of
Range(TableName & "[PART NUMBER]")
Try changing it to range like:
ActiveWorkbook.Worksheets(TableName).Range("A1")
That will sort using column "A" as the first sort key.
Related
I'm working on a code to filter my table, but I'm struggling to set the 'Key:=Range("")' , so far I've tested a code without setting Dims and it works, but I want a more pratical approach, so the code will work in all worksheets (active worksheet) in my workbook.
Error im getting: Method range of object _'Global' failed. Error 1004
So on resume, im new on VBA and dont now how to set MyTable(Tbl) on the 'Key:=Range("Tbl[[#All],[Column1]]")
Sub MAKE_FILTER()
Dim ws As Worksheet
Dim wb As Workbook
Set wb = ThisWorkbook
Set ws = ActiveSheet
Dim Tbl As Object
Set Tbl = ws.ListObjects(1)
Tbl.Range.AutoFilter Field:=1, Criteria1:=RGB(255, 255, 0), Operator:=xlFilterCellColor
Tbl.Sort.SortFields.Clear
Tbl.Sort.SortFields.Add2 Key:=Range("Tbl[[#All],[DANFE]]"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With Tbl.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Tbl.Sort.SortFields.Clear
Tbl.Sort.SortFields.Add2 Key:=Range("Tbl[[#All],[Nº NF-e]]"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With Tbl.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Without DIMs:
Sub Macro1() 'without DIMs
ActiveSheet.ListObjects("Tabela14212255").Range.AutoFilter Field:=1, _
Criteria1:=RGB(255, 255, 0), Operator:=xlFilterCellColor 'ok
ActiveWorkbook.Worksheets("NOVEMBRO 2022").ListObjects("Tabela14212255").Sort. _
SortFields.Clear 'ok
ActiveWorkbook.Worksheets("NOVEMBRO 2022").ListObjects("Tabela14212255").Sort. _
SortFields.Add2 Key:=Range("Tabela14212255[[#All],[DANFE]]"), SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("NOVEMBRO 2022").ListObjects("Tabela14212255"). _
Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.Worksheets("NOVEMBRO 2022").ListObjects("Tabela14212255").Sort. _
SortFields.Clear
ActiveWorkbook.Worksheets("NOVEMBRO 2022").ListObjects("Tabela14212255").Sort. _
SortFields.Add2 Key:=Range("Tabela14212255[[#All],[Nº NF-e]]"), SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("NOVEMBRO 2022").ListObjects("Tabela14212255"). _
Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
You can use:
Key:=tbl.Listcolumns("Nº NF-e").Range
to refer to the column by name.
Filter and Sort Tables (ListObjects)
Sub ApplyFilter()
Dim Headers() As Variant: Headers = Array("DANFE", "No NF-e")
' Reference 'ActiveSheet' and 'ThisWorkbook'.
If ActiveSheet Is Nothing Then Exit Sub ' no visible workbooks open
If Not TypeOf ActiveSheet Is Worksheet Then Exit Sub ' not a worksheet
Dim ws As Worksheet: Set ws = ActiveSheet
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
If Not ws.Parent Is wb Then
MsgBox "This only works for worksheets in the workbook containing " _
& "this code named '" & wb.Name & "' and located in '" _
& wb.Path & "'.", vbCritical
Exit Sub
End If
' Reference the table.
Dim lo As ListObject
On Error Resume Next
Set lo = ws.ListObjects(1) ' the first table
On Error GoTo 0
If lo Is Nothing Then
MsgBox "The worksheet '" & ws.Name & "' doesn't contain any tables.", _
vbExclamation
Exit Sub
End If
' Filter and sort.
With lo
If .ShowAutoFilter Then ' autofilter arrows are turned on
' Clear all filters.
If .AutoFilter.FilterMode Then .AutoFilter.ShowAllData
End If
.Range.AutoFilter 1, RGB(255, 255, 0), xlFilterCellColor
Dim lc As ListColumn, n As Long
For n = LBound(Headers) To UBound(Headers)
' Reference the column.
On Error Resume Next
Set lc = .ListColumns(Headers(n))
On Error GoTo 0
If lc Is Nothing Then
MsgBox "No column named '" & Headers(n) & "' in the table " _
& "named '" & .Name & "' of worksheet '" _
& .Parent.Name & "'.", vbCritical
Exit Sub
End If
' Sort by the column.
With .Sort
With .SortFields
.Clear
.Add2 lc.Range, xlSortOnValues, xlAscending, , xlSortNormal
End With
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Set lc = Nothing ' reset for the next iteration
Next n
End With
End Sub
For testing macro purposes, I am trying to do the following command on the spreadsheet ( Copy/highlight existing data in a given spreadsheet and then try to sort). However, when i tried to apply the same macro in another new workbook. I know in the following command- it is only locked to Worksheets("sheet1")- how should i change this so that i can apply in other excels(new workbooks) that have a different name as well?
Cells. Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range("A2:A3") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A2:B3")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
many thanks!
Sort 'Pattern' for Different Worksheets
The first procedure is an example of how to use the second one (the solution).
Replace Sheet1 with the name of your worksheet.
Option Explicit
Sub sortWorksheetTEST()
Dim wb As Workbook
' Pick one:
Set wb = ThisWorkbook ' the workbook containing this code
'Set wb = ActiveWorkbook ' an active workbook, the one you're looking at
'Set wb = Workbooks("Test.xlsx") ' an open workbook
'Set wb = Workbooks.Open("C:\Test\Test.xlsx") ' a workbook to be opened
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
sortWorksheet ws
' or e.g. without any of the previous
'sortWorksheet ActiveSheet
End Sub
Sub sortWorksheet(ByVal ws As Worksheet)
On Error GoTo clearError
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add2 Key:=ws.Range("A2:A3"), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
With ws.Sort
.SetRange ws.Range("A2:B3")
.Header = xlGuess ' you don't want VBA to decide: xlYes or xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ProcExit:
Exit Sub
clearError:
MsgBox "Run-time error '" & Err.Number & "':" & Err.Description
Resume ProcExit
End Sub
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
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
My problem with the code below is that because of the select of the range that I have defined I can't run this code successfully while on another Sheet. I know that it's bad practice to use .select and now I know why, it causes so many problems. I'm not sure how to fix this code so that it'll work properly.
Sub Sorting(sorted As Range, keys As Range)
'Range("A1:A4").Select
sorted.Select
Sheets("IDBHour1").Sort.SortFields.Clear
Sheets("IDBHour1").Sort.SortFields.Add Key:=keys, SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortTextAsNumbers
With Sheets("IDBHour1").Sort
.SetRange sorted
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
You don't need to select in order to sort. How are you passing the ranges in the calling procedure?
My personal preference would be to pass the ranges as strings and then make them into ranges inside the sub. That code runs from anywhere. The IDBHour1 sheet needs neither selection nor activation.
Sub Sorting(sortSheet As String, sorted As String, keys As String)
Dim ws As Worksheet
Dim sortRange As Range
Dim sortKeys As Range
Set ws = ThisWorkbook.Sheets(sortSheet)
Set sortRange = ws.Range(sorted)
Set sortKeys = ws.Range(keys)
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=sortKeys, SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortTextAsNumbers
With ws.Sort
.SetRange sortRange
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Sub testSort()
Call Sorting("IDBHour1", "A1:A10", "A1")
End Sub