有保护页时如何保持macros运行?

我使用密码保护了工作表4,因为在工作表4的单元格中有一些单元格不允许用户input。密码是1234。

但是,我想运行我的macros,如果有错误,单元格会自动突出显示。

我的macros不运行,错误,因为我想突出显示的单元格在受保护的工作表。

如何使工作表4保持受保护状态,并使我的macros保持运行,当我点击validationbutton?

Private Sub commandbutton1_click() FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:=1234, WriteResPassword:=1234, _ ReadOnlyRecommended:=False, CreateBackup:=False vehicle = Sheets("4").Range("K22") expenditure_gasoline = Sheets("4").Range("M22") If vehicle = true and expenditure_gasoline = 0 Then MsgBox "it should not be empty", vbcritical End If If vehicle = true and expenditure_gasoline = 0 Then Sheets("4").Range("M22").Interior.ColorIndex = 3 End sub 

尝试更改下面(未经testing)


V1 – 保护工作表免受用户更改,但不能更改VBA UserInterfaceOnly:=True


 Option Explicit Private Sub commandbutton1_click() Const PATH_AND_FILENAME = "C:\YourTestFile.xlsx" '<------ Update this path & file name Dim wb As Workbook, ws As Worksheet, vehicle As Variant, expenditureGasoline As Variant Set wb = Workbooks.Open(Filename:=PATH_AND_FILENAME, WriteResPassword:="1234", _ Password:="1234", Format:=xlOpenXMLWorkbookMacroEnabled) Set ws = wb.Sheets("4") ws.Protect Password:="1234", UserInterfaceOnly:=True '<--- Protect changes from UI only Set vehicle = ws.Range("K22") Set expenditureGasoline = ws.Range("M22") If Not IsError(vehicle) And Not IsError(expenditureGasoline) Then If vehicle = True And expenditureGasoline = 0 Then ws.Range("M22").Interior.ColorIndex = 3 MsgBox "Cell M22 should not be empty", vbExclamation End If End If End Sub 

V2 – 在更改之前解除保护,并在更改后保护


 Private Sub commandbutton1_click() Const PATH_AND_FILENAME = "C:\YourTestFile.xlsx" '<------ Update this path & file name Dim wb As Workbook, ws As Worksheet, vehicle As Variant, expenditureGasoline As Variant Set wb = Workbooks.Open(Filename:=PATH_AND_FILENAME, WriteResPassword:="1234", _ Password:="1234", Format:=xlOpenXMLWorkbookMacroEnabled) Set ws = wb.Sheets("4") Set vehicle = ws.Range("K22") Set expenditureGasoline = ws.Range("M22") If Not IsError(vehicle) And Not IsError(expenditureGasoline) Then If vehicle = True And expenditureGasoline = 0 Then ws.Unprotect "1234" '<--- Unprotect it before the change ws.Range("M22").Interior.ColorIndex = 3 ws.Protect "1234" '<--- Protect it back, after the change MsgBox "Cell M22 should not be empty", vbExclamation End If End If End Sub