VBA代码不激活单元格

时间:2016-11-24 01:40:37

标签: excel vba excel-vba

我的代码看起来有问题。但是,我无法解决问题。 我在工作簿上有2个选项卡。主要表和子表。 选择"是"在主工作表的下拉列表中将启用子工作表进行输入。 选择"否"在主工作表的下拉列表中将禁用子工作表上的单元格。

我的问题:当我选择"否"时,我看不到"活动细胞"在任何床单上。我所说的Active Cell是我们点击单元格时获得的绿色边框(附带截图)。 enter image description here

主页上的代码

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
        If Not Intersect(Target, Range("R12")) Is Nothing Then
            If Target.Value = "YES" Then 
                Call Enabler 
            Else 
                Call Disabler
            End If
        End If
    Application.EnableEvents = True
End Sub

模块代码

Public Sub Disabler()
     With ThisWorkbook.Sheets("SubSheet")
         .Unprotect Password:="xyz"
         .Range("E13:E14").Locked = True
         .Protect Password:="xyz"
     End With
End Sub

Public Sub Enabler()
     With ThisWorkbook.Sheets("SubSheet")
         .Unprotect Password:="xyz"
         .Range("E13:E14").Locked = False
         .Protect Password:="xyz"
     End With
End Sub

2 个答案:

答案 0 :(得分:0)

以下内容对您有用......

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo ExitSub
    Application.EnableEvents = False
    If Target.Address <> "$R$12" Then Exit Sub
    If Target.Value = "YES" Then
        Call LockRange(False)
    Else
        Call LockRange(True)
    End If

ExitSub:
    Application.EnableEvents = True
End Sub

Private Function LockRange(bFlag As Boolean) As Boolean
    On Error Resume Next
    With ThisWorkbook.Sheets("SubSheet")
        .Unprotect Password:="xyz"
        .Range("E13:E14").Locked = bFlag
        .Protect Password:="xyz"
        'Debug.Print bFlag
    End With
    LockRange = True
End Function

答案 1 :(得分:0)

我想你必须输入:

.EnableSelection = xlNoRestrictions

顺便说一句,您可能希望通过 Disabler()Enabler()个子合并到一个Sub来缩短您的代码:

Public Sub DisableSubSheet(disable As Boolean)
    With ThisWorkbook.Worksheets("SubSheet")
        .Unprotect Password:="xyz"
        .Range("E13:E14").Locked = disable
        .Protect Password:="xyz"
        .EnableSelection = xlNoRestrictions '<--| make it possible for user to select cells
    End With
End Sub

因此,更改您的Worksheet_Change事件处理程序代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    If Not Intersect(Target, Range("R12")) Is Nothing Then
        If Target.Value = "YES" Then
            DisableSubSheet False '<--| in place of previous 'Call Enabler'
        Else
            DisableSubSheet True '<--| in place of previous 'Call Disabler'
        End If
    End If
    Application.EnableEvents = True
End Sub