0

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

6
  • 2
    Try ThisWorkbook instead of ActiveWorkbook Commented Aug 16, 2019 at 14:09
  • @Dean that is probably the syntax I need, will test. Cheers. So simple... Commented Aug 16, 2019 at 14:11
  • 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. Commented Aug 16, 2019 at 14:20
  • Hmmm, unfortunately I get an "object required" error when using ThisSheet.Protect Commented Aug 16, 2019 at 14:21
  • 1
    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. Commented Aug 16, 2019 at 14:22

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.