我有一个宏来保护前7行。当用户尝试编辑内容时,它会显示一个消息框"The cell or chart that you are trying to change is protected and therefore read-only."
。
贝尔沃是宏观......
Function columnNumberToLetter(columnNumber As Long) As String
Dim vArr
vArr = Split(Cells(1, columnNumber).Address(True, False), "$")
columnNumberToLetter = vArr(0)
End Function
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lastColumn As Long
Dim theFirtCellOfHeader As String
Dim theLastCellOfHeader As String
Dim headerRange As String
Set sht = Sheets(1)
theFirtCellOfHeader = "A1"
lastColumn = sht.Cells(7, Columns.Count).End(xlToLeft).Column
theLastCellOfHeader = columnNumberToLetter(lastColumn) & 7
headerRange = theFirtCellOfHeader & ":" & theLastCellOfHeader
ActiveSheet.Unprotect
Cells.Locked = False
Range(headerRange).Locked = True
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
End Sub
有没有办法显示自定义错误消息而不是默认消息框?
答案 0 :(得分:1)
尝试使用此代码保护前七行并显示自定义错误消息:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim goodRng As Range
If Target.Locked Then
Application.EnableEvents = False
Sheet1.Range(8 & ":" & 100).Locked = False 'set to desired unlocked rows
Application.EnableEvents = True
MsgBox "Stop!" & vbNewLine & vbNewLine & _
"The cell(s) you are trying to alter are protected" & vbNewLine & _
"and should not be altered without prior" & vbNewLine & _
"authorization." & vbNewLine & vbNewLine & _
"Thank you," & vbNewLine & _
"Management", vbCritical, "STOP!"
End If
End Sub
我不能因为代码的基础而受到赞扬,我从Zack Barresse @ MrExcel.com采用了它。我只是改变它以达到你的目的。
注意:我已解锁行8-100,可随意调整要锁定的工作表的数量(65536是电子表格行的最大数量)。
希望它有所帮助!
答案 1 :(得分:0)
NJMR,
这个怎么样?将其从选择更改为更改,并将撤消语句放入其中,以便删除用户输入的任何更改,然后给出错误。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim goodRng As Range
If Target.Locked Then
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
Sheet1.Range(8 & ":" & 65536).Locked = False 'set to desired unlocked rows
MsgBox "Stop!" & vbNewLine & vbNewLine & _
"The cell(s) you are trying to alter are protected" & vbNewLine & _
"and should not be altered without prior" & vbNewLine & _
"authorization." & vbNewLine & vbNewLine & _
"Thank you," & vbNewLine & _
"Management", vbCritical, "STOP!"
End If
End Sub