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
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
I have a number of sheets with the same template where I want to sort the date field. I've been doing it manually but am trying VBA to do it for me. I have the code below which works but it applies to more sheets than I'd like. I am trying to figure out how to stop the macro to stop at a specific sheet and end it there.
Goal: have macro run from sheet 1-10, stop # sheet 10 or if worksheet = Sheet 11 then stop. I am using sheet 1-10, 11 as simple references. I'd insert the specific sheet name.
I found some answers online with -
If ws.Name <> "" Then
end with
but am not sure where to input it within my macro below.
Sub Macro1()
'
' sortbydate2 Macro
'
'
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
With ws
With .Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A2:a49"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange ws.Cells
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
Next ws
End Sub
Thank you,
P1
Manipulate All Worksheets Except...
You can implement an 'exceptions array' where you would preferably
place the names, or the indexes (not recommended) of the unwanted
worksheets.
Then you can use IsError with Application.Match to check if the name of the current worksheet has been found in the 'exceptions array'.
The Code
Option Explicit
Sub Macro1()
'
' sortbydate2 Macro
'
'
Dim Exceptions As Variant
Exceptions = Array("Sheet11", "Sheet12") ' add more or less.
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If IsError(Application.Match(ws.Name, Exceptions, 0)) Then
With ws
With .Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A2:a49"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.SetRange ws.Cells
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
End If
Next ws
End Sub
You could loop through all worksheets within the workbook and apply the filter to all except - something like:
For Each ws In ActiveWorkbook.Worksheets
if ws.Name <> "IDontWantFilters" Then
with ws
....
end with
end if
next ws
I think this should work. I assume once it gets to sheet11 you just want it to stop completly
Sub Macro1()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
if ws.name = "Sheet11" then
exit sub
end if
With ws
With .Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A2:a49"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange ws.Cells
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
Next ws
End Sub
If you only want to sort the first 10 worksheets, you could do a basic loop to accomplish your task...
Dim ws As Worksheet
For i = 1 To 10
Set ws = Sheets(i)
With ws.Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A2:A49"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange Sheets(i).Cells
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next i
Here is the code that I am using to apply sorting to each page except two. The system is throwing following error.
"select method of range class failed".
Private Sub CommandButton3_Click()
Dim ws1 As Worksheet
For Each ws1 In Worksheets
If ws1.Name <> "Sheet1" And ws1.Name <> "Extra" Then
**ws1.Range("A1:V1000").Select** Something is wrong here I suspect
ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Clear
ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Add Key:=Range("I2:I1000") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Add Key:=Range("T2:T1000") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(ws1).Sort
.SetRange Range("A1:V1000")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End If
Next ws1
End Sub
Please help.
I would Select the worksheet before Selecting the range. Replace:
ws1.Range("A1:V1000").Select
with:
ws1.Select
Range("A1:V1000").Select
You may not need these Selections if you use .Range() rather than Range() in the code that follows. Also since ws1 is a worksheet object,:
ActiveWorkbook.Worksheets(ws1)
should be replace with:
ActiveWorkbook.Worksheets(ws1.Name)
There may be other problems with code.
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.
I'm running a VBA script from an Excel file that opens another file, manipulates data and some charts, then saves it. Everything works perfectly except when I try to sort data. When I get to the line .SortFields.Add Key:=Range("J3:J11")... I get an error
Run-time error '-2147417851 (80010105)':
Automation error
The server threw an exception
I'm sure it has something to do with the way I'm referencing the Excel object, but I've tried everything and can't seem to find a solution. The sorting code was borrowed from the macro recorder and modified.
Private Sub button1_Click()
Dim path As String
Dim exl As Excel.Application
path = ActiveWorkbook.path & "\"
Set exl = CreateObject("Excel.Application")
With exl
.Workbooks.Open path & "bin\Integrated UPSIDE with Summary.xlsm"
<...other code...>
With .Worksheets("Summary").Sort
.SortFields.Clear
.SortFields.Add Key:=Range("J3:J11") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange Range("C2:P11")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
<...other code...>
.Workbooks.Close
End With
exl.QUIT
End Sub
Any suggestions are GREATLY appreciated! Thanks
The problem is you aren't correctly referencing your Ranges. The sort code you are using was written for sorting ranges on the active worksheet in the current instance of Excel.
The simplest way to fix this is to reference the ranges as being in the other instance of Excel.
.SortFields.Add Key:=exl.Worksheets("Summary").Range("J3:J11") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange exl.Worksheets("Summary").Range("C2:P11")
However, my suggestion would be to use the Workbook and Worksheet objects instead.
Private Sub button1_Click()
Dim path As String
Dim exl As Excel.Application
Dim wbk As Workbook, sht As Worksheet
path = ActiveWorkbook.path & "\"
Set exl = CreateObject("Excel.Application")
With exl
Set wbk = .Workbooks.Open(path & "bin\Integrated UPSIDE with Summary.xlsm")
'<...other code...>
Set sht = wbk.Worksheets("Summary")
With sht.Sort
.SortFields.Clear
.SortFields.Add Key:=sht.Range("J3:J11") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange sht.Range("C2:P11")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'<...other code...>
wbk.Close
Set sht = Nothing
Set wbk = Nothing
End With
exl.Quit
End Sub