VBA protect script problem

ddoyle67

New Member
Joined
Apr 4, 2013
Messages
46
Office Version
  1. 365
Platform
  1. Windows
I have a workbook where I have inserted a command button to run a code to hide a range of cells then un-hide them when pressed again, that line works perfect. My problem is the workbook is protected so I added 2 lines of code to un-protect it and then re-protect it. how ever I get a runtime error 9 script out of range. When I debug it says my first line and un-protect line are bad. The first line works fine without the protection lines. This is what I have written. Do I need something before my un-protect line? I have written the un-protect and protect lines a couple different ways (sh.unprotect "david") and still get the same error. I am new to VBA and learning as I have been creating this workbook.

Private Sub CommandButton3_Click()

Sheets("Sheet2").Unprotect Password:="david"

Columns("O:T").Hidden = Not Columns("O:T").Hidden

Sheets("Sheet2").Protect Password:="david"

End Sub
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
How about
VBA Code:
Private Sub CommandButton3_Click()

Me.Unprotect Password:="david"

Columns("O:T").Hidden = Not Columns("O:T").Hidden

Me.Protect Password:="david"

End Sub
 
Upvote 0
You're welcome & thanks for the feedback
 
Upvote 0

Forum statistics

Threads
1,215,686
Messages
6,126,202
Members
449,298
Latest member
Jest

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top