Excel Macro: Apply sorting to each sheet - excel

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.

Related

Excel - VBA Macro - Stopping code at a specific sheet

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

VBA Excel sort the data from A to Z in one column with all data table changes

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

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

A more flexible sort

I created a macro to sort a list of customer names and it works however as you can see below it sorts the list that now goes from A2 through A47. I'm worried that when the size of the list grows or contracts my macro will not work properly. How can I adjust this so that my sort macro works in any list running down column A. Thank you.
Sub ByCustomerName()
'
' ByCustomerName Macro
' Sorts by Customer Name
'
'
ActiveWorkbook.Worksheets("My Customers").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("My Customers").Sort.SortFields.Add Key:=Range( _
"A2:A47"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("My Customers").Sort
.SetRange Range("A1:B47")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
You just need to set your range rather than hard-coding it\
Change .SetRange Range("A1:B47")
At the top of the code try
Dim sortRange As Range
Dim lastRow As Long
Dim ws As Worksheet
Set ws = Sheet1
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Set sortRange = Range("A1:B" & lastRow)
Then .SetRange sortRange
Try Range("A1", Range("A1").End(xlDown))
This should select all non-empty rows starting with A1.

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