Question

I have three different Subs available in a VBA module and wanted to call those series of Subs from an unique Sub activated through a VBA button.

Below the code running:

Sub Updateworkbook()

Call Unprotectworkbook
Call CopyAndPaste
Call Protectworkbook

End Sub

After the first Sub Unprotectworkbook() is run the other Sub are not called and executed. Why this happens?

Below the Unprotectworkbook() Sub code for your reference

Sub Unprotectworkbook()

 Dim myCount
    Dim i
    myCount = Application.Sheets.Count
    Sheets(1).Select
    For i = 1 To myCount
        ActiveSheet.Unprotect "password"
        If i = myCount Then
            End
        End If
        ActiveSheet.Next.Select
    Next i

End Sub
Was it helpful?

Solution

Modify your code as follows (change End to Exit Sub):

Sub Unprotectworkbook()

 Dim myCount
    Dim i
    myCount = Application.Sheets.Count
    Sheets(1).Select
    For i = 1 To myCount
        ActiveSheet.Unprotect "password"
        If i = myCount Then
            Exit Sub
        End If
        ActiveSheet.Next.Select
    Next i

End Sub

or you can simply change it to the next one:

Sub Unprotectworkbook()
    Dim sh   
    For Each sh In Sheets
       sh.Unprotect "password"
    Next 
End Sub

OTHER TIPS

It is very hard to answer your question without seeing the code in all three subs.

Some pointers though:

  1. You don't need to select each sheet in order to modify it - just use Sheet(i).Unprotect "password" in the for loop instead.

  2. Also, since you have a for loop you don't need to code when it should end, if you have defined the For i = 1 To myCount statement correctly. In other words, remove the If i = myCount Then End part.

  3. You could define the For loop like the following: For i = 1 To Application.Sheets.Count to simplify your code, then you can remove the myCount variable.

  4. You should always define your variables with a datatype in order to minimize errors, e.g use Dim i As Integer instead.

  5. Always use Option Explicit at the top of each module, also to minimize confusion and errors caused by typos etc.

I strongly advise you to run through a couple of tutorials on VBA, there are lots around. The following is just the first one up when searching, I haven't tried it: Excel VBA Basic Tutorial 1

If this helps, I recommend making another set of 3 subs to test blank items first. Otherwise use one of the other answers above.

Sub msgTEST0()    'Call msgTEST0
  Call msgTEST1
  Call msgTEST2
  Call msgTEST3
End Sub


Sub msgTEST1()
    MsgBox "MSG1" & Space(10), vbQuestion
End Sub

Sub msgTEST2()
    MsgBox "MSG2" & Space(10), vbQuestion
End Sub

Sub msgTEST3()
    MsgBox "MSG3" & Space(10), vbQuestion
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top