I am new to
VBA, I need help applying the below VBA code to two specific work sheets
by Region and
by Model. The code simply finds the last column which has the name
total for the year and copies the previous months values into a new column. The code works fine if executed on each worksheet separately.
Sub Insert_New_Col() Dim R As Range, BeforeR As Long 'Find 'Totals' in row 5 of active sheet Set R = Rows(3).Find(what:="Total for the Year", lookat:=xlWhole) 'identify the column to copy (last month) BeforeR = R.Column - 1 If R Is Nothing Then MsgBox ("The word 'Totals' was not found in Row 5 - macro terminated!") Exit Sub ElseIf Not R Is Nothing Then 'copy last month's column Columns(BeforeR).Copy 'insert copied cells before the Totals column Columns(R.Column).Insert Shift:=xlRight Application.CutCopyMode = False End If End Sub
Create an array of sheets to loop through. The way this is set up, you can add as many sheets to the array as you need without any need to modify the macro. You will need to modify your
msgbox since you no longer exit the sub when it fails to find a specified value – instead, you move on to the next sheet.
Sub Insert_New_Col() Dim Found As Range, BeforeR As Long Dim ws As Worksheet, xSheets As Variant Dim i As Long xSheets = Array("Sheet1", "Sheet2") '<-- List of sheets to loop through For i = LBound(xSheets) To UBound(xSheets) Set ws = xSheets(i) Set Found = ws.Rows(3).Find(What:="Total for the Year", Lookat:=xlWhole) BeforeR = R.Column - 1 If Found Is Nothing Then MsgBox ("The word 'Totals' was not found in Row 5 on Sheet: " & ws.Name) Else Columns(BeforeR).Copy ws.Columns(R.Column).Insert Shift:=xlRight End If Next i End Sub
If your code works on 1 sheet, it can work on many.
Create a function with your code inside
and an argument of worksheet – something like:
myFunction(ws as Worksheet)
In another function or sub do this:
Dim myWorkSheets(2) As Worksheet Set myWorkSheets(0) = Worksheets("Region") '-- or Worksheets(1) Set myWorkSheets(1) = Worksheets("Model") '-- or Worksheets(2) For Each ws In myWorkSheets myFunction (ws) Next
or if you want to apply to all work sheets:
For Each ws In ActiveWorkbook.Worksheets myFunction (ws) Next
In ‘myFunction’ place ‘ws’ before ranges, cells, etc. e.g:
Set R = ws.Rows(3).Find(what:="Total for the Year", lookat:=xlWhole)