Macro not protecting every sheet

G

Guest

Below is the macro used and it did not password protect every sheet in the
workbook. At the time that the macro was ran there were some sheets that we
hidded - some were very hidden. But that shouldn't make a difference should
it?

I have about 30 sheets in the workbook.

Sub lockdown()
Const pword As String = "XXXX"
Dim sht As Worksheet
For Each sht In Worksheets
sht.Protect pword
Next sht
End Sub
 
G

Guest

I don't know - but see if this does better:
Sub lockdown()
Const pword As String = "XXXX"
Dim sht As Worksheet, sh as Worksheet
set sh = Activesheet
Application.ScreenUpdating = False
For Each sht In Worksheets
hval = sht.Visible
sht.visible = xlSheetVisible
sht.Select
sht.Protect pword
sht.Visible = hval
Next sht
sh.Select
Application.ScreenUpdating = True
End Sub
 
G

Guest

Out on a limb here but are they all worksheets or are some of them chart
sheets or macro sheets... If so then you want to go through the Sheets
collection and not the worksheets collection...
 
G

Guest

What should the hval be set as -- constant?

Tom Ogilvy said:
I don't know - but see if this does better:
Sub lockdown()
Const pword As String = "XXXX"
Dim sht As Worksheet, sh as Worksheet
set sh = Activesheet
Application.ScreenUpdating = False
For Each sht In Worksheets
hval = sht.Visible
sht.visible = xlSheetVisible
sht.Select
sht.Protect pword
sht.Visible = hval
Next sht
sh.Select
Application.ScreenUpdating = True
End Sub
 
G

Guest

Figured out what the problem was - the sheets were already protected but not
password protected. When I unprotected the sheets, the original macro worked
fine.

What should I have done differently to make the macro work whether the sheet
was protected or not??
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top