For loop with nested 'with...end with' [duplicate] - vba

This question already has answers here:
Excel VBA For Each Worksheet Loop
(4 answers)
Closed 7 years ago.
So I'm trying to use a -with...end with-
within a -for..next- loop. The idea is to get all these things on every sheet. Code below is pseudo
For Sheet = Sheet1 to Sheet10
With Sheet
...code
End With
Next
So I have 10 sheets. Sheet1, Sheet2, Sheet3, etc
What I can't seem to figure out is how to loop through all these sheets

you should try this answer
https://stackoverflow.com/a/21918281/1214743
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
ResizeColumns WS
Next WS
You could create an array of the worksheet names and then foreach through them, if you don't want to select every Worksheet in the Workbook.

Dim ws As Excel.Worksheet
Dim iIndex As Integer
For iIndex = 1 To ActiveWorkbook.Worksheets.count
Set ws = Worksheets(iIndex)
ws.Activate
'Do something here.
ws.Range("A2").Value = "SomeValue"
Next iIndex

The way you did it does not work because Sheet will not be an object. The for each solutions below will give you a sheet object and allow you to use with.
Dim wks as Worksheet
For Each wks in ThisWorkbook.Worksheets
With wks
...
End With
Next
Should work

Dim wsTemp as Worksheet
For each wsTemp in Worksheets
wsTemp.activate
'Do something
Next wsTemp

Related

VBA For Loop Only Altering One Sheet

I'm trying to alter the values in a range of cells for specifically named worksheets only.
The workbook I am editing has around 95 sheets, and I only want to change the sheets with the period actual information (named P1W1, P1W2 etc, up to P12W5).
When i execute the below it only alters the first sheet and then exits the macro.
Any help is much appreciated
Option Explicit
Public Sub periodclear()
Dim ws As Worksheet
Dim r As Range
On Error Resume Next
Set r = Range("c10:i30")
For Each ws In Worksheets
If ws.Name Like ("P#W#") Or ws.Name Like ("P##W#") Then
r.Value = ""
End If
Next ws
End Sub
Try this. Your r was defined only in terms of one sheet so needs to be brought inside the loop.
Public Sub periodclear()
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name Like ("P#W#") Or ws.Name Like ("P##W#") Then
ws.Range("c10:i30").ClearContents
End If
Next ws
End Sub

Delete duplicate values within single worksheet, for multiple worksheets in workbook

I have a workbook with 102 worksheets. I want to cycle through each worksheet independently and remove duplicates within that worksheet (not across the workbook as a whole).
I currently have this code:
Sub DeleteDuplicates()
Set ws = ThisWorkbook.Worksheets
For Each X In ws
X.Range("A:B").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
Next
End Sub
I believe it is deleting duplicates that appear anywhere in the workbook, not just within a single worksheet. Is there a way to limit this code so that it only removes duplicates from within the specific worksheet it is operating on?
This cycles through each worksheet in your workbook. You can specify worksheets if you need to skip any by adding IF statements.
Public Sub DeleteDuplicates()
Dim ws as Worksheet
Dim wb as Workbook
Set wb = ThisWorkbook
For Each ws In wb.Worksheets
ws.Range("A:B").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
Next ws
End Sub

Excel VBA - Copy range from one sheet paste to all sheets after certain sheet in workbook

I feel like this is too simple to be stuck on, but I have a workbook with about 100 sheets, and I need to copy a range from one sheet (Sheet2 Range a1:H200) to Sheet5 AF1:AM200 and every sheet after (Sheet5 through Sheet100 or more). I have tried creating a loop and copying the original range and pasting to each sheet, but it hasn't worked. I feel like this is the closest I've gotten
Sub CopyPasteLoop()
Dim wsVar As Worksheet
For Each wsVar In ThisWorkbook.Sheets
With wsVar
ThisWorkbook.Worksheets("Sheet2").Range("A1:H200").Value = ThisWorkbook.Worksheets("Sheet5").Range("AF1").Value
End With
Next wsVar
End Sub
I feel like it should be simpler, but I can't make it work. Thanks!
Almost there. Try this:
Sub CopyPasteLoop()
Dim wsVar As Worksheet
Dim i as Integer
For i = 5 to ThisWorkbook.Worksheets.Count
ThisWorkbook.Worksheets(i).Range("AF1:AM200").Value = ThisWorkbook.Worksheets("Sheet2").Range("A1:H200").Value
Next i
End Sub
Or for better performance, use this:
Dim vRange as Variant
vRange = ThisWorkbook.Worksheets(2).range("A1:H200")
Dim i as Integer
For i = 5 to ThisWorkbook.Worksheets.Count
ThisWorkbook.Worksheets(i).Range("AF1:AM200").Value = vRange
Next i
Hopefully #Scott Holtzman's answer will work for you (providing your sheets are indexed in the same order as they're named). This approach will also work.
Dim wb As Workbook, ws As Worksheet
Dim rng As Range
Set wb = ThisWorkbook
Set rng = wb.Sheets("Sheet2").Range("A1:H200")
For Each ws In wb.Sheets
If CInt(Right(ws.Name, Len(ws.Name) - Len("Sheet"))) >= 5 Then
ws.Range("AF1:AM200").Value = rng.Value
End If
Next ws

Excel VBA: Counting Data in Column from Another Workbook and Inputting Counter in Master Workbook

I need to create a macro in my CountResults.xlsm (Master Workbook) that solves the following problem. I have a column of data in another worksheet with either YES or NO. I need to come up with a macro that counts the amount of "YES" in the column. The column is located in Sheet2 of the workbook Test01.xlsx. Then take that count and put it in one cell in my CountResults.xlsm file. Like so:
I have a code that displays a count for a column in the same sheet. But this code does not count when there are 'breaks' in the column (empty spaces) like I have in my picture. This is that code:
Private Sub CommandButton1_Click()
MsgBox Range("A1").End(xlDown).Row
Range("A1").End(xlDown).Offset(1, 0).Select
End Sub
I have another code that helps with accessing another workbook and defining values for each workbook and worksheet:
Dim wbSource As Workbook
Dim wbTarget As Workbook
Dim shSource As Worksheet
Dim shTarget As Worksheet
Set wbSource = Workbooks.Open(Filename:="C:\Users\khanr1\Desktop\Test_Excel\Test03.xlsm", ReadOnly:=True)
Set wbTarget = ThisWorkbook
Set shSource = wbSource.Worksheets("Sheet2")
Set shTarget = wbTarget.Worksheets("Sheet1")
Use COUNTIF. It will give you the total even if the range is in another workbook. i.e. =COUNTIF([Book2.xlsx]Sheet2!$D$2:$D$9, "Yes"). Problem with having COUNTIF within your sheet as a formula is that you will need to open the other workbook if you want the count to be update. Below VBA code will perform an update for you. Assign the sub to a button in your CountResults.xlsm workbook
EDIT: Added row count as per OP's requirement
Sub UpdateResults()
Dim oWBWithColumn As Workbook: Set oWBWithColumn = Application.Workbooks.Open("<your Test01.xlsx address here>")
Dim oWS As Worksheet: Set oWS = oWBWithColumn.Worksheets("Sheet2")
Dim intLastRow as Integer: intLastRow = oWS.Cells(Rows.Count, "B").End(xlUp).Row
ThisWorkbook.Worksheets("<name of the sheet in your CountResults.xlsm workbook>").Range("<cell address>").Value = Application.WorksheetFunction.CountIf(oWS.Range("B2:B" & intLastRow), "yes")
oWBWithColumn.Close False
Set oWS = Nothing
Set oWBWithColumn = Nothing
End Sub

VBA Macro across multiple worksheets

I am trying to run a single macro which performs functions on multiple worksheets. Let's say I have assigned the macro button on worksheet 4. I have listed the functions I want it to perform step by step:
1) Select certain cells in worksheet 4 and copy to adjacent cells in worksheet 4.
2) delete range of cells in worksheet 3.
3) CUT range of cells in worksheet 2 then paste this range of cells into worksheet 3.
4) Take range of cells from a separate workbook and copy into worksheet 2. (I know this is an entirely different problem as the workbook is automatically published and I will have to find a way to link the two.)
5) Update pivot tables located within Worksheet 4 and Worksheet 3.
I would love help on the first 3 functions of this. I've pasted my current code below.
Sub START()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim sh4 As Worksheet
Set sh1 = ActiveWorkbook.Sheets("Brand")
Set sh2 = ActiveWorkbook.Sheets("CurrentWeek")
Set sh3 = ActiveWorkbook.Sheets("PriorWeek")
Set sh4 = ActiveWorkbook.Sheets("Pivot")
sh4.Range("B29:B30").Select
Selection.Copy
sh4.Range("C29").Select
ActiveSheet.Paste
sh3.Range("A4:AC1000").Select
Selection.Delete
sh2.Range("A4:AC1000").Select
Selection.Copy
sh3.Range("A4").Select
ActiveSheet.Paste
End Sub
It works... but it only works when I'm in the right worksheet to perform a specific function.
By removing the select, the selection and the activesheet, you will be able to make this sheet-independent
Sub START()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim sh4 As Worksheet
Set sh1 = ActiveWorkbook.Sheets("Brand")
Set sh2 = ActiveWorkbook.Sheets("CurrentWeek")
Set sh3 = ActiveWorkbook.Sheets("PriorWeek")
Set sh4 = ActiveWorkbook.Sheets("Pivot")
sh4.Range("B29:B30").Copy sh4.Range("C29")
sh3.Range("A4:AC1000").Delete
sh2.Range("A4:AC1000").Copy sh3.Range("A4")
End Sub
You are off to a great start. Just little more refinement and you'll have it.
Basically, there's no need to .Select your ranges (sheets, workbooks, etc), at least in this case. You can work directly with them and by using the Copy supply the destination where they will be copied.
See code below:
Sub START()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim sh4 As Worksheet
Dim wkb As Workbook
Set wkb = Workbooks("wkbName") '-> best to call workbooks by name, as opposed to "ActiveWorkbook", also best to set it to object
With wkb '-> now we can work with this object directly and succinctly
Set sh1 = .Sheets("Brand")
Set sh2 = .Sheets("CurrentWeek")
Set sh3 = .Sheets("PriorWeek")
Set sh4 = .Sheets("Pivot")
sh4.Range("B29:B30").Copy sh4.Range("C29")
'sh3.Range("A4:AC1000").Delete -> you don't need this if you are overwritting it
sh2.Range("A4:AC1000").Copy sh3.Range("A4")
End With
End Sub
sheets("name1").range("B29:B30").copy Destination:=sheets("name2").range("C29")
Will copy from one to another sheet assuming the sheet names are name1 and name2
Sub START()
Sheet("Pivot").Range("B29:B30").Copy Sheet("Pivot").Range("C29")
Sheet("CurrentWeek").Range("A4:AC1000").Copy Sheet("PriorWeek").Range("A4")
End Sub