Excel - VBA Macro - Stopping code at a specific sheet - excel

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

Related

Using the same macro in a different spreadsheet

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

How do I adjust this code which sorts a single sheet so that it sorts multiple sheets in a workbook

I'm running a macro which takes data from one sheet and copies into several other worksheets. I want to adjust the following code so that I can sort ALL worksheets in my workbook by Column Q once it's been copied and not just the sheet named "Sorted1"
ActiveWorkbook.Worksheets("Sorted1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sorted1").Sort.SortFields.Add2 Key:=range("D2:D" & lastrow _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sorted1").Sort
.SetRange range("A1:Q" & lastrow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
You can call sheets not only by their name, but also by their position in your workbook.
sheets("sheet1") <- calls sheet named "sheet1"
sheets(1) <- calls the first sheet
If you want your script to iterate through all sheets, you can use a for-loop and replace the sheet-name by the iterative variable.
for i = 1 to x 'replace x with number of sheets
ActiveWorkbook.Worksheets(i).sort (your script)...
....
Next
If the number of sheets changes sometimes, use the following command instead of x to count the number of sheets
Application.Sheets.Count
So:
for i = 1 to Application.Sheets.Count
ActiveWorkbook.Worksheets(i).sort (your script)...
....
Next
Try the next code, please:
Sub sortAllSheets()
Dim sh As Worksheet, wb As Workbook, LastRow As Long
Set wb = ActiveWorkbook
For Each sh In wb.Worksheets
'if all the columns have the same number of rows, this can be done for all the code
LastRow = sh.Range("D" & Rows.Count).End(xlUp).row
sh.Sort.SortFields.Clear
sh.Sort.SortFields.Add2 key:=sh.Range("D2:D" & LastRow) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With sh.Sort
.SetRange sh.Range("A1:Q" & LastRow) 'if LastRow is the same as in D:D
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next
End Sub

Excel Macro: Apply sorting to each sheet

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.

Issue with SortFields function and ranges

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

How can I only sort thru the rows with data?

I have a macro that sorts the rows by a specific column, the problem is I'm manually setting the range for the number of rows to sort (i.e. A2:A174) every time I add a new row. How can I change my code so that it sorts all the rows with data only so I don't have to go into the code and change the range every time I add a new row.
Sub SortByName()
SortByName Macro
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A2:A174") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:H174")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A1").Select
End Sub
Sub SortByDate()
Thanks so much in advance for your wisdom!
something like this which looks for the last cell in A to mark the range.
Sub SortByName()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("Sheet1")
Set rng1 = ws.Range(ws.[a1], Cells(Rows.Count, "A").End(xlUp))
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=rng1 _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange rng1.Resize(rng1.Rows.Count, 8)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Application.Goto ws.[a1]
End Sub

Resources