gpt4 book ai didi

vba - 有 protected 工作表时如何保持宏运行?

转载 作者:行者123 更新时间:2023-12-04 20:56:49 25 4
gpt4 key购买 nike

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

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

我的宏没有运行并且出错,因为我要突出显示的单元格位于 protected 工作表中。

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

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

最佳答案

尝试以下更改(未经测试)

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

关于vba - 有 protected 工作表时如何保持宏运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46147302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com