How do I avoid run-time error when a worksheet is protected in MS-Excel?

后端 未结 2 558
-上瘾入骨i
-上瘾入骨i 2020-12-03 18:30

The code snippet below changes the data validation state of a cell and runs when the Excel-2003 worksheet is unprotected. However, when I protect the work sheet the macro do

2条回答
  •  时光说笑
    2020-12-03 18:46

    If I understand the question correctly, you will be the one protecting the sheet. If that is the case, you can use the following VBA:

    myWorksheet.Protect contents:=True, userinterfaceonly:=True
    

    The key part here is "userinterfaceonly:=true". When a worksheet is protected with this flag set, VBA macros are still allowed to make changes.

    Place this code into the WorkBook_Activate event to automatically protect the workbook and set the flag whenever it is activated.

    Edit: Thanks to Lance Roberts for his recommendation to use Workbook_Activate instead of Workbook_Open.

    Edit: Since the above didn't seem to work, you may have to wrap the failing portion of your VBA code with unprotect/protect commands. If you do that, I would also wrap the entire macro with an error handler, so that the sheet is not left unprotected after an error:

    Sub MyMacro
        On Error Goto HandleError
    
        ...
    
        myWorksheet.unprotect
        With ModifyCell.Validation
            ...
        End With
        myWorksheet.protect contents:=True, userinterfaceonly:=True
    
        ...
    
    Goto SkipErrorHandler
    HandleError:
        myWorksheet.protect contents:=True, userinterfaceonly:=True
        ... some code to present the error message to the user
    SkipErrorHandler:
    End Sub
    

    Edit: Have a look at this thread at PCreview. They went through much the same steps, and came to the same conclusion. At least you're not alone!

提交回复
热议问题