You are here:

Excel/How to use variables with Worksheet Unprotect


In Excel v2010, I have a workbook with 30 worksheets, each named after a sales rep (firstname lastname) e.g. Bob Smith.  Each sheet is protected with a password; I'm declaring variables in a module for both the username (which is the same as the sheet name) and password for the sheet.
The username variables are U1, U2, etc.  
The password variables are Up1, Up2, etc.
The following example is just for the 1st 2 sheets:

Public Const U1 As String = "Bob Smith"
Public Const U2 As String = "Linda Jones"
Public Const Up1 As String = "BS"  'password for Bob Smith
Public Const Up2 As String = "LJ"  'password for Linda Jones

Currently I have code that will unprotect each sheet, e.g.
Worksheets(U1).Unprotect Up1
Worksheets(U2).Unprotect Up2

While that code works, I'd much rather do this in a For Next loop; something like the following:
Dim x as string, y as string
For i = 1 to 30
x = "U"&i
y = "Up"&i
Worksheets(x).Unprotect y

But of course that doesn't work.
Obviously I'm doing something stupid; can you tell me what I'm doing wrong.
Many thanks for your expertise.

Hello Al,

Apologies for the delayed response. I've created the below code which could meet your requirements. Please let me know if this is helpful:

For each sheet, you need to add the Case "xxxx  yyyy" and Pwd = "xy" lines in the below code after the last case and just before the wsheet.unprotect... line.

Public Sub prtct()
   Dim wSheet          As Worksheet
   Dim Pwd          As String

   For Each wSheet In Worksheets
   Select Case ActiveSheet.Name
   Case "Bob Smith"
   Pwd = "BS"
   Case "Linda Jones"
   Pwd = "LJ"
   wSheet.Unprotect Password:=Pwd
   End Select
   Next wSheet
End Sub

Hope this helps,
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts




I can answer questions related to the following topics: 1. MS Excel - Creating and Linking Formulae, Running Pivot Tables, Vlookup etc. 2. Macros / VBA - Creating Macros to do specific jobs. Importing / Exporting / Validating Data in excel through Macros.


I've been working on excel for over 10 years and on VBA macros for over 3 years now.

Bachelor of Commerce, Chartered Accountant from The Institute of Chartered Accountants of India

©2017 All rights reserved.

[an error occurred while processing this directive]