Forum Discussion
gms4b
Sep 13, 2019Brass Contributor
VBA: loop not looping
I am trying to have VBA go through each sheet in a workbook, look for the phrase "Sample Name", and delete all of the rows above it. It will find the phrase and delete the rows above for the first wo...
- Sep 13, 2019
Here is the proper way to do that...
Sub LoopforSub() Dim Ws As Worksheet Dim MyRange As Range Dim r As Long Application.ScreenUpdating = False For Each Ws In ActiveWorkbook.Worksheets 'Setting MyRange on each worksheet Set MyRange = Ws.Range("A:A").Find("Sample Name", LookIn:=xlValues) 'If Sample Name is found in column A, MyRange will be properly set If Not MyRange Is Nothing Then r = MyRange.Row 'If Sample Name is in A1 that means the rows on that Sheet has already been deleted 'And if you run your existing code, it will produce an error because there is no Row#0 If r <> 1 Then r = r - 1 'Delete Rows on the Sheet in the loop Ws.Rows(r & ":" & 1).Delete End If End If Set MyRange = Nothing Next Ws Application.ScreenUpdating = True End Sub
PReagan
Sep 13, 2019Bronze Contributor
I would suggest modeling your code based on the following:
https://support.microsoft.com/en-us/help/142126/macro-to-loop-through-all-worksheets-in-a-workbook
https://support.microsoft.com/en-us/help/142126/macro-to-loop-through-all-worksheets-in-a-workbook
- gms4bSep 13, 2019Brass Contributor
yeah, ugh. I've tried both of these and neither seems to work. It just never moves on to the second sheet. It just starts applying the code to the same sheet it just did.
I have the workbook attached.
- Subodh_Tiwari_sktneerSep 13, 2019Silver Contributor
The code I posted above works perfectly on your sample file.
Please test it and let me know if that works fine on your end too.
The problem with your earlier code was, you were setting MyRange variable on the ActiveSheet and you never activated another sheet inside the For Loop.
- gms4bSep 13, 2019Brass Contributor