excel - 如何阻止用户在特定单元格范围内修改超过 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
解决方案
你可能想试试这个代码。
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。
无论如何,这只是为了展示方法。该解决方案只是敷衍地测试。如果您在测试时出现错误,请告诉我,我会修复它们。
推荐阅读
- python - 如何四面体每个面的体积偏移
- python - 将数组作为值传递时,Python Wordpress REST API 返回 False
- c++ - 需要帮助将函数存储为变量并打印出变量
- python - 如何在没有日期值的python中删除行?
- spring-boot - 连接两个表,并在 thymeleaf 表中显示检索到的信息
- x11 - 为什么使用xming作为远程X11服务器时,uxterm和xterm需要很长时间才能打开?
- virtual-reality - VZsoft 误导
- javascript - 在主函数中使用 React Native Await/Async
- java - Jbehave 测试配置和测试报告未按预期工作
- excel - Powershell复制/粘贴各种多行