0 votes
in VBA by Beginner (8 points)

Hi guys

I found the following code:

Sub Protect_Sheets()
' Loop through all sheets in the workbook
For I = 1 To Sheets.Count
' Activate each sheet in turn.
Sheets(I).Activate
response = MsgBox("Do you want to protect this sheet?", vbYesNo)
If response = vbYes Then
ActiveSheet.Protect Password:="****", DrawingObjects:=True, _
Contents:=True, Scenarios:=True
ElseIf response = vbNo Then
MsgBox ("Sheet not protected")
End If
Next I
End Sub

I have been using this successfully - but is there an easy way to perhaps modify it so that instead of looping through the entire workbook, it could just lock every sheet with the exception of "Sheet1" and "Sheet2"?

The other constraints are that I don't know how many sheets they may be in every book I need to use this on :(

Thanks in advance!

 

1 Answer

+1 vote
by Skilled (605 points)
selected by
 
Best answer

Try this code

Sub Protect_Sheets()
    Dim ws As Worksheet
    
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Sheet1" And ws.Name <> "Sheet2" Then
            ws.Protect Password:="****", DrawingObjects:=True, Contents:=True, Scenarios:=True
        End If
    Next ws
End Sub

 

by Beginner (8 points)
Thanks sooooo much!!!!

That's perfect!
by Skilled (605 points)
You're welcome. Glad I can offer little help.

Welcome to wellsr Q&A
wellsr Q&A is the VBA and Python programming community that rewards you for learning how to code.

Getting Started
Register
VBA Cheat Sheets (On Sale Now)

Earn free prizes for asking VBA and Python questions and for answering questions asked by others in our community.

What makes us different?
Our points system rewards you with a chance for free gifts based on the quality of your questions and answers. All you have to do is post and you could get rewarded, like these members:

runfunke $10 Amazon Gift Card
coolag $10 Amazon Gift Card
Siew Hun $10 Amazon Gift Card

So, why don't you join us? It really is an encouraging way to motivate members in our VBA and Python community.

Register

For more programming tips visit the VBA Tutorials Blog and the Python Tutorials Blog.

...