首页 > 解决方案 > 如何阻止用户在特定单元格范围内修改超过 2 个单元格值

问题描述

我有一个在用户选择工作职位时自动填写的表格,但是在 3 个部分中我有下拉列表(B21:B45、B27:B30、B50:B67),并且用户将被允许从这些下拉列表中更改最多 2 个选项-向下列表。

换句话说,我有一个表 B21:C45,如果用户将修改 B 列中 25 个单元格中的 2 个,那么宏将自动给出一条消息,说明您已修改了最大单元格数,然后宏将锁定单元格 B21:B45。这同样适用于其他 2 个表(对于 RngTwo 和 RngThree)。

我尝试使用 Intersect 函数,但我不确定如何编写一个宏来锁定特定范围的单元格,如果此范围内的 2 个单元格发生更改。对我来说最大的挑战是宏需要考虑所有 3 个范围。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim RngOne As Range
    Dim RngTwo As Range
    Dim RngThree As Range

    Set RngOne = Range("B21:B45")
    Set RngTwo = Range("B27:B30")
    Set RngThree = Range("B50:B67")

    If Not Application.Intersect(RngOne, Range(Target.Address)) Is Nothing Then
        MsgBox "You changed " & Target.Count & " out of " & RngOne.Count & " cells."
    End If
End Sub

标签: excelvba

解决方案


你可能想试试这个代码。

Private Sub Worksheet_Change(ByVal Target As Range)
    ' 048

    Static Count(1 To 3)    As Integer
    Dim Rng                 As Range
    Dim i                   As Integer          ' array index

    If Target.CountLarge > 1 Then Exit Sub
    Set Rng = Application.Union(Range("B21:B25"), Range("B27:B30"), Range("B50:B67"))
    For i = 1 To 3
        If Not Application.Intersect(Rng.Areas(i), Target) Is Nothing Then
            If Count(i) < 2 Then
                Count(i) = Count(i) + 1
            Else
                MsgBox "You have exceeded the maximum number (2)" & vbCr & _
                       "of permissible changes in this section." & vbCr & _
                       "This change will be rolled back.", _
                       vbInformation, "Too many changes"
                With Application
                    .EnableEvents = False
                    .Undo
                    .EnableEvents = True
                End With
            End If
            Exit For
        End If
    Next i
End Sub

您设置的三个范围是重叠的,一旦您指定了真正的意思,就需要更精确的编码。目前我只是假设其中一个地址中有一个类型,并将第一个范围设置为 B21:B25 而不是 B21:B45。

无论如何,这只是为了展示方法。该解决方案只是敷衍地测试。如果您在测试时出现错误,请告诉我,我会修复它们。


推荐阅读