VBA在单击受保护的单元格时抛出提示

时间:2016-10-05 12:59:41

标签: excel vba excel-vba

我有工作簿,Sheet / workbook都受到保护。 我有一个代码来锁定/禁用某些范围的单元格,当下拉值为“no”时,解锁/启用当下拉值为“是”时 然而,我想要禁用的下拉值和单元格位于不同的工作表上。

“主页”下拉列表 “子表”上的单元格范围

我还需要在用户点击受保护范围时以及当该值设置为“否”时向用户发出提示。

我在“主页”上使用以下代码

Private Sub Worksheet_Change(ByVal Target As Range)
Dim worksh As Integer
Dim worksheetexists As Boolean
Dim str1 As String

If UCase$(Range("E30").Value) = "YES" Then
               Sheets("SubSheet").Select
               Sheets("SubSheet").Range("E20:I3019").Locked = False
               Sheets("SubSheet").Range("E20:I3019").Activate
           Else
                Sheets("SubSheet").Range("E20:I3019").Locked = True
End If
End Sub

按照子表格中的代码

Private Sub WorkBook_SheetChange(ByVal sh as Object, ByVal Target as Range)
If Intersect (Target, sh.Range("$E$19:$I$3000")) Is Nothing Then Exit Sub
MsgBox "Please select the appropriate dropdown on MAIN Sheet " & Target.Address
With Application
    .EnableEvents = False
    .UnDo
    .EnableEvents = True
End With
End Sub

不确定,我在哪里出错,因为当用户点击受保护的单元格时,它不会抛出提示。

1 个答案:

答案 0 :(得分:1)

首先。您应该删除Sheets("SubSheet").Select。如果您运行代码并且不在工作表内,则可能会发生错误。尝试做:

with ThisWorkbook.Sheets("SubSheet")
  If UCase$(Range("E30").Value) = "YES" Then
    .Range("E20:I3019").Locked = False
    .Range("E20:I3019").Activate
  Else
    .Range("E20:I3019").Locked = True
  End If
end with

二。您没有返回目标范围。我的意思是你的Private Sub WorkBook_SheetChange等待ByVal Target作为参数而你的Private Sub Worksheet_Change会返回任何值。它应该是一个返回你为我选择的范围或单元格的函数。

编辑:

with ThisWorkbook.Sheets("SubSheet")
  If UCase$(Range("E30").Value) = "YES" Then
    .Range("E20:I3019").Locked = False
  Else
    .Range("E20:I3019").Locked = True
     WorkBook_SheetChange Range("E20:I3019")
  End If
end with

并且

Private Sub WorkBook_SheetChange(ByVal Target as Range)
    If Intersect (Target, Range("$E$19:$I$3000")) Is Nothing Then Exit Sub
    MsgBox "Please select the appropriate dropdown on MAIN Sheet " &    Target.Address
    With Application
       .EnableEvents = False
       .UnDo
       .EnableEvents = True
    End With
 End Sub