如果有受保护的纸张,如何保持宏运行?

时间:2017-09-11 02:09:21

标签: excel vba excel-vba validation

我使用密码保护工作表4,因为有些单元格不允许用户在工作表4的这些单元格中输入。密码为1234.

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

我的宏没有运行和错误,因为我要突出显示的单元格位于受保护的工作表中。

当我点击验证按钮时,如何使工作表4保持受保护并让我的宏继续运行?

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

1 个答案:

答案 0 :(得分:0)

尝试下面的更改(未经测试)

V1 - 保护工作表免受用户更改,但不保护VBA更改private static limit = 10; ... public static void decreaseLimit() { if (limit > 2) limit--; } ... // Inside your drawSquares method if (size > limit){ ... } else return;

UserInterfaceOnly:=True

V2 - 在更改前取消保护,并在更改后进行保护

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
相关问题