当用户尝试编辑受保护的单元格时,显示自定义错误消息

我有一个macros保护前7行。 它显示一个消息框"The cell or chart that you are trying to change is protected and therefore read-only." 当用户尝试编辑内容时。 贝沃是macros观…

 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 

有没有办法显示自定义错误消息,而不是默认消息框?

试试这个代码将保护前七行,并显示一个自定义的错误消息:

 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行,可以随意调整要locking的表格的多less(65536是电子表格行的最大数量)。

希望能帮助到你!

NJMR,

这个怎么样? 将其从“select”更改为“更改”,并将撤销语句放入,以便删除用户input的任何更改,然后发出错误。

 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