Code to be run on multiple specific sheets - vba

I want to run a code on multiple sheets. The sheet names are: Sheet1, Sheet2, 1, 2 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 and Summary. I define my sheets of interest= (1, 2, 3, 4 and Summary). The code should run only on these sheets. If any sheet in sheets of interest is not present, it should run for all other sheet of interest, i.e. if 1,2 are not present it should run for 3,4 and Summary.

you can loop each sheets into your workbook
Option Explicit
Dim ws As Worksheet, a As Range
Sub forEachWs()
For Each ws In ActiveWorkbook.Worksheets
Call yourcode
Next
End Sub

For Each sht In ThisWorkbook.Sheets
If sht.Name <= 12 Then
'
'
'MsgBox sht.Name
End If
Next

As an alternative to For...Next Loop this will work on all worksheets that are numbered:
Sub AllSheets()
Dim wrkSht As Worksheet
For Each wrkSht In ThisWorkbook.Worksheets
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Or any workbook.worksheets reference: '
'For Each wrkSht In ActiveWorkbook.Worksheets '
'For Each wrkSht In Workbooks("Book2.xlsx").Worksheets '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If IsNumeric(wrkSht.Name) Then
'Your code here.
End If
Next wrkSht
End Sub
As a complete alternative you could put the required sheet names in a range in the workbook, give the range a defined name and use this:
Sub All()
Dim rCell As Range
Dim wrkSht As Worksheet
For Each rCell In Range("MyDefinedSheetNameRange")
If WorkSheetExists(rCell.Value) Then
Set wrkSht = ThisWorkbook.Worksheets(rCell.Value)
'Do stuff with wrksht
End If
Next rCell
End Sub
Public Function WorkSheetExists(SheetName As String) As Boolean
Dim wrkSht As Worksheet
On Error Resume Next
Set wrkSht = ThisWorkbook.Worksheets(SheetName)
WorkSheetExists = (Err.Number = 0)
Set wrkSht = Nothing
On Error GoTo 0
End Function

This is a very basic question and you should find the answer by simply Googling it. Though here combined with this is the answer for you.
Sub WorksheetLoop()
Dim WS_Count As Integer
Dim I As Integer
Dim found As Integer
Dim index As Integer
Dim sheetnames {"1", "2", "Summary"}
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For I = 1 To WS_Count
found = 0;
For index = 0 To numbers.GetUpperBound(0)
If sheetnames(index) = ActiveWorkbook.Worksheets(I).Name Then
found = 1
EndIf
Next
If found = 1 Then
' Insert your code here.
' The following line shows how to reference a sheet within
' the loop by displaying the worksheet name in a dialog box.
MsgBox ActiveWorkbook.Worksheets(I).Name
EndIf
Next I
End Sub

Related

Updating my workbook

I have created a Workbook that is used in various different computers.
Sometimes I add features to it and I would like to easily update it.
The idea is whenever I have a new version of it, I take it to a new computer, save in a temp file and copy the sheets where the data is stored.
Based on the answers I have edit my first draft to: (I didn't know that both workbooks needed to be opened at the same time)
Private Sub CommandButton1_Click()
Dim sh As Worksheet
Dim ws As Worksheet
Dim wb As Workbook
Dim wn As Workbook
Set wn = Workbooks("Reception")
Set wb = Workbooks("Reception2")
With wb
.Sheets("Pass").Range("A1") = "flh"
For Each ws In .Worksheets
Select Case .Name
Case "Formularios", "Coordenador", "LookupList", "Pass"
'Do nothing
Case Else
ws.Delete
End Select
Next ws
End With
With wn
For Each sh In .Worksheets
Select Case .Name
Case "Formularios", "Coordenador", "LookupList", "Pass"
'Do nothing
Case Else
sh.Copy After:=wb.Sheets(wb.Sheets.Count)
End Select
Next sh
End With
End Sub
Case at moment is not working and macro deletes every sheet no matter the name
Thank you all for the feedback
You can find the temp folder by using Environ("temp"), but from your code I'm not sure this is the folder you're using.
This code has a couple of functions to check if the workbook exists and is already open. One other bit of code I'd add is to disable any code in Reception.xlsm from firing when it's opened.
Public Sub MyProcedure()
Dim ws As Worksheet
Dim wb As Workbook
Dim wn As Workbook
Dim Rec1Path As String
Dim Rec2Path As String
Rec1Path = "c:\save\Reception.xlsm"
Rec2Path = "c:\temp\Reception2.xlsm"
'Open or set a reference to Reception.xlsm.
If WorkBookExists(Rec1Path) Then
If WorkBookIsOpen(Rec1Path) Then
'Don't need path for open workbook, just name.
'InStrRev finds last occurrence of "\" (same as InStr, but in Reverse).
Set wn = Workbooks(Mid(Rec1Path, InStrRev(Rec1Path, "\") + 1))
Else
Set wn = Workbooks.Open(Rec1Path)
End If
End If
'Open or set a reference to Reception2.xlsm.
If WorkBookExists(Rec2Path) Then
If WorkBookIsOpen(Rec2Path) Then
Set wb = Workbooks(Mid(Rec2Path, InStrRev(Rec2Path, "\") + 1))
Else
Set wb = Workbooks.Open(Rec2Path)
End If
End If
With wb
.Worksheets("Pass").Range("A1") = "flh"
For Each ws In .Worksheets
Select Case .Name
Case "Formularios", "Coordenador", "LookupList", "Pass"
'Do nothing
Case Else
'You don't really need the count of worksheets if you can guarantee
'you're not going to try and delete the last remaining sheet.
If .Worksheets.Count > 1 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
End Select
Next ws
End With
With wn
'Re-using the ws variable.
For Each ws In .Worksheets
Select Case .Name
Case "Formularios", "Coordenador", "LookupList", "Pass"
'Do nothing
Case Else
ws.Copy After:=wb.Sheets(wb.Sheets.Count)
End Select
Next ws
End With
End Sub
Public Function WorkBookExists(sPath As String) As Boolean
WorkBookExists = Dir(sPath) <> ""
End Function
Public Function WorkBookIsOpen(FullFilePath As String) As Boolean
Dim ff As Long
On Error Resume Next
ff = FreeFile()
Open FullFilePath For Input Lock Read As #ff
Close ff
WorkBookIsOpen = (Err.Number <> 0)
On Error GoTo 0
End Function
Is the workbook open when you try to 'SET' it? If not you will need to open it as such:
Dim wb As Workbook
Set wb = Workbooks.Open("c:\temp\Reception.xlsm")
With some more googling I was able to craft the code that I wanted in the end.
Here is the answer for the curious or for other people looking to do the same:
Private Sub CommandButton1_Click()
Dim sh As Worksheet
Dim ws As Worksheet
Dim LastRow As Long
Dim LastCol As Long
Dim j As Long
Dim Rng As Range
Dim wb As Workbook
Dim wn As Workbook
Set wn = Workbooks("Reception")
Set wb = Workbooks("Reception2")
With wb
.Sheets("Pass").Range("A1") = "flh"
For Each ws In .Worksheets
Select Case ws.Name
Case "Formularios"
'Do nothing
Case "Coordenador"
'Do nothing
Case "LookupList"
'Do nothing
Case "Pass"
'Do nothing
Case Else
With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set Rng = .Range(.Cells(2, 1), .Cells(LastRow, LastCol))
Rng.ClearContents
End With
End Select
Next ws
End With
With wn
For Each sh In .Worksheets
Select Case sh.Name
Case "Formularios"
'Do nothing
Case "Coordenador"
'Do nothing
Case "LookupList"
'Do nothing
Case "Pass"
'Do nothing
Case Else
For j = 1 To wb.Sheets.Count
If sh.Name = wb.Worksheets(j).Name Then
On Error Resume Next
sh.Range("A:J").Copy wb.Worksheets(j).Range("A1")
End If
Next j
End Select
Next sh
End With
Application.CutCopyMode = False
End Sub
Thanks to #Darren Bartrup-Cook for the help.

Counting cells of worksheets within another workbook

I have one xlsm file with a single button in it which, when clicked, is supposed to open a separate workbook and search through all contained worksheets for cells of a specific colour.
The problem is, instead of searching the other workbook's worksheets, it just searches itself. I'm new to VBA, and feel like i've been round the internet 6 times trying to solve this. What am I doing wrong here?
Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim holdCount As Integer
Dim cellColour As Long
Dim cell As Range, rng As Range
Set wb = Workbooks.Open("blahblahblah.xls")
Set rng = Range("A1:A20")
holdCount = 0
cellColour = RGB(255, 153, 0)
For Each ws In wb.Worksheets
For Each cell In rng
If cell.Interior.Color = cellColour Then
holdCount = holdCount + 1
End If
Next cell
Next ws
MsgBox "found " & holdCount
End Sub
It looks to me like you aren't fully qualifying your Range
Move this inside of your ws loop instead of where it is now.
Set rng = ws.Range("A1:A20")
BraX pointed out that I needed to qualify the Range WITHIN the For Each ws loop, so here is the fixed and working code. Again, all credit to Brax.
Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim holdCount As Integer
Dim cellColour As Long
Dim cell As Range, rng As Range
Set wb = Workbooks.Open("blahblahblah.xls")
holdCount = 0
cellColour = RGB(255, 153, 0)
For Each ws In wb.Worksheets
With ws
Set rng = ws.Range("A1:A20")
For Each cell In rng
If cell.Interior.Color = cellColour Then
holdCount = holdCount + 1
End If
Next cell
End With
Next ws
MsgBox "found " & holdCount
End Sub

Type mismatch error VBA loop through worksheets

I keep getting a type mismatch error and have tried changing the type a few times. I'm just trying to loop through each worksheet and a specified range to see if that word exists in every cell of that range.
Sub CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Dim strCheck As Range
Set arrVar = ActiveWorkbook.Worksheets
'MsgBox (arrVar)
For Each ws In arrVar
If ws.Range("C9:G20").Value = "Word" Then
MsgBox (True)
End If
Next ws
End Sub
When you have a range with many columns, it creates an array.
Taking the array into consideration like so:
Sub CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Dim strCheck As Range
Set arrVar = ActiveWorkbook.Worksheets
'MsgBox (arrVar)
For Each ws In arrVar
For each col in ws.Range("C9:G20").Cells
if col.Value = "Word" Then
MsgBox (True)
end if
End If
Next ws
End Sub
You can't get the value of ws.Range("C9:G20") and compare it to one string. You've selected multiple cells. If you want to return True when nay one of these cells contains "Word" or when all of them contain "Word" you'll need to iterate over them.
This is an example of how to return whether or not your range contains "Word" anywhere at least once
Function CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Set arrVar = ActiveWorkbook.Worksheets
For Each ws In arrVar
Dim c
For Each c In ws.Range("C9:G20").Cells
If c = "Word" Then
CheckWord = True
Exit Function
End If
Next c
Next ws
End Function
Sub CheckWord()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If Not ws.Range("C9:G20").Find(What:="Word", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False) Is Nothing Then MsgBox "Found in " & ws.Name
Next ws
End Sub

Looping through different sheets

I would appreciate your help with the macro I am trying to create.
I have an xls file with a bunch of worksheets, some of which named "1", "2", "3", and so forth. I would like to create a macro that loops only through those 'number-named' worksheets, hence NOT according to the index as in the code below. (Sheet "1" is not the first sheet in the workbook). Before the loop I need to define both the cell range and sheets.
Below is my (wrong) attempt.
Sub Refresh ()
Dim i As Integer
Dim rng As Range
Set rng = Range("A10:TZ180")
For i = 1 To 30
Sheets(i).Activate
rng.Select
rng.ClearContents
Application.Run macro:="xxx"
Next i
End Sub
dim w as worksheet
for each w in activeworkbook.worksheets
if isnumeric(w.name) then
w.range("A10:TZ180").clearcontents
xxx()
end if
next
If the macro "xxx()" requires a selected range you just need to add a select statement. (Borrowing from GSerg)
Dim w As Worksheet
For Each w In ActiveWorkbook.Worksheets
If IsNumeric(w.Name) Then
w.Range("A10:TZ180").ClearContents
w.Range("A10:TZ180").Select
Application.Run macro:="xxx"
End If
Next
To clear up your misunderstanding about assigning a range see the following:
Sub Refresh()
Dim ws As Worksheet
Dim rng As Range
Dim i As Integer
For Each ws In ActiveWorkbook.Worksheets
If IsNumeric(ws.Name) Then
'you must activate the worksheet before selecting a range on it
ws.Activate
'note the qualifier: ws.range()
Set rng = ws.Range("A10:TZ180")
'since the range is on the active sheet, we can select it
rng.Select
rng.ClearContents
Application.Run macro:="xxx"
End If
Next
End Sub
Sub test2()
Dim ws As Worksheet
Dim rg As Range
Dim arrSheets As Variant
arrSheets = Array("Sheet1", "Sheet2", "Sheet3")
Dim x As Long
For x = LBound(arrSheets) To UBound(arrSheets)
Set ws = Worksheets(arrSheets(x))
ws.Activate
'...
Next
End Sub
Sub test3()
Dim ws As Worksheet
Dim x As Long
For x = 1 To 20
Set ws = Worksheets(CStr(x))
ws.Activate
'...
Next
End Sub
try this
Sub main()
Dim shtNames As Variant, shtName As Variant
shtNames = Array(1, 2, 3, 4) '<== put your actual sheets "number name"
For Each shtName In shtNames
With Worksheets(CStr(shtName))
.Range("A10:TZ180").ClearContents
.Range("A10:TZ180").Select
Application.Run macro:="MacroToRun"
End With
Next shtName
End Sub
Sub MacroToRun()
MsgBox "hello from cells '" & Selection.Address & "' in sheet '" & ActiveCell.Parent.Name & "'"
End Sub

How can I set a worksheet object based on a worksheet's codename?

The worksheet name may change. Because of that I want to set the worksheet object based on the worksheet's codename. How can I do this?
My best attempt so far is:
Sub UpdateNameDropdown()
Dim wksName As String
wksName = ThisWorkbook.Sheets(Sheet16).Name
Dim wks As Worksheet
Set wks = Sheets(wksName)
End Sub
But I get a type mismatch error on the row wksName = ThisWorkbook.Sheets.Sheet16.Name
This?
Sub Sample()
Dim wks As Worksheet
Set wks = Sheet16
With wks
Debug.Print .Name
'~~> Do what you want
End With
End Sub
This uses the codename as a String
Sub CodeIt()
Dim CodeName As String
CodeName = "Sheet1"
Dim WS As Worksheet, GetWorksheetFromCodeName As Worksheet
For Each WS In ThisWorkbook.Worksheets
If StrComp(WS.CodeName, CodeName, vbTextCompare) = 0 Then
Set GetWorksheetFromCodeName = WS
Exit For
End If
Next WS
MsgBox GetWorksheetFromCodeName.Name
End Sub
Thank you Gary's Student. I midified your function to the following:
Function GetWorksheetFromCodename(codeName As String) As Worksheet
Dim wks As Worksheet
For Each wks In ThisWorkbook.Worksheets
If StrComp(wks.codeName, codeName, vbTextCompare) = 0 Then
Set GetWorksheetFromCodename = wks
Exit For
End If
Next wks
End Function