0

I am currently learning VBA.

I am watching this series of tutorial videos on youtube regarding how to use VBA to use a loop and if statement to create dupes of my sheets and how to delete them.

I changed my code to the following:

Sub deleteloop()       
    Dim x As Worksheet    
    Dim y As String
    Dim z As String

    Application.DisplayAlerts = False

    For Each x In ActiveWorkbook.Sheets        
        y = x.Name     
        z = VBA.right(y, 3)       
        If z = "(2)" Then
            ActiveSheet.delete           
        End If
    Next x

    Application.DisplayAlerts = True
End Sub

As you can imagine, my duplicated sheets have "(2)" at the end of their string, so the idea is for my code to delete any duplicated sheets using this.

The problem is that it deletes all the duplicated sheets but the last one, and I have to run it again to delete the last remaining sheet with "(2)" at the end.

What am I doing wrong here?

1 Answer 1

3

Change ActiveSheet.delete to x.delete as you want to delete the sheet you're examining, not the one that's currently active.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.