0
votes

What is the best way of protecting a specific Excel workbook?

I have an inherited script that includes the following common lines at the end:

ActiveSheet.Protect "my-password"
ActiveWorkbook.Protect "my-password"

However, I've noticed that as the script can take a few minutes to run users often switch to a new unrelated workbook whilst it solves - whatever else they are working on. The password protection is then inherited by the unrelated workbook upon the completion of the macro - since whatever other Excel file the user is working within is now "Active" (presumably? this is my reading of the problem).

The above script is in a workbook that can be renamed to whatever the user chooses, and be saved in any number of directories. How can I ensure that only the original excel file is locked/unlocked by the Macro, when other workbooks are in use?

I am sure there are many ways to do this, but which is the most foolproof method?

NOTE: using office 365

1
Try ThisWorkbook instead of ActiveWorkbook - Dean
@Dean that is probably the syntax I need, will test. Cheers. So simple... - Petrichor
You might want to also store the ActiveSheet to a worksheet object in the event your users are changing workbooks., You will then be able to still reference that "ActiveSheet" regardless if they change workbooks. - Dean
Hmmm, unfortunately I get an "object required" error when using ThisSheet.Protect - Petrichor
Yeah ThisSheet does not exist. You will be able to use ThisWorkbook as a Workbook object. To use a Worksheet object I would recommend reading my comment above yours. - Dean

1 Answers

0
votes

Thanks Dean's answers in the comments:

Early in the code (and in Worksheet_Change if appropriate) enter the following to define your sheet as an object (named default_ws in my case):

Set default_ws = ActiveSheet

When you are ready to lock your sheet or workbook you can then use:

default_ws.Protect "password-here" 'protect your sheet
ThisWorkbook.Protect "password-here" 'protect your workbook

Also note:

You could also define your workbook as an object as follows if desired:

Set default_wb = ActiveWorkbook