简体   繁体   中英

How to protect a specific workbook only in Excel VBA

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM