我创建了一个脚本,该脚本为我提供了对我的数据选项卡所做更改的审核日志(我想为用户提供访问权限以进行一次性更改,因此不想完全锁定和保护该选项卡) .
当用户选择 1 个单元格时,这完全正常,但是,当用户选择多个单元格并尝试删除或更改它们时,脚本会崩溃。
需要哪一行代码才能不允许用户选择多个单元格,或者如果他们选择了,则生成一个弹出窗口,提示他们只能选择 1 个单元格。
Dim PreVal
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'This sets our previous value once we have selected the cell value to change
PreVal = Target.Value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim LastRow
'If we change the cell we selected then the worksheet change event is triggered
If Target.Value <> PreVal Then
LastRow = Worksheets("Logged Changes").Cells(Rows.Count, 2).End(xlUp).Row
'If the new value of the cell is not the same a previous value then logging of details begins
Worksheets("Logged Changes").Cells(LastRow, 2).Offset(1, 0).Value = _
Application.UserName & " changed cell " & Target.Address _
& " from " & PreVal & " to " & Target.Value
End If
End Sub ```
答案 0 :(得分:1)
您可以通过检查 Selection.Count
结果来发现这一点。
最简单的形式:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Checks for the count of selected cells and only assigns PreVal if = 1
If Not Selection.Count > 1 Then
PreVal = Target.Value
Else
MsgBox "You can only select 1 cell at a time.", VbCritical + VbOkOnly, "To Many Cells Selected!"
End If
End Sub
您也可以使用 Target.Count
而不是 Selection.Count
来编写它。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Checks for the count of selected cells and only assigns PreVal if = 1
If Not Target.Count > 1 Then
PreVal = Target.Value
Else
MsgBox "You can only select 1 cell at a time.", VbCritical + VbOkOnly, "To Many Cells Selected!"
End If
End Sub
这只会在所选单元格的数量不大于 1 时分配 PreVal = Target.Value
(并且考虑到如果没有选择任何内容则不会触发该功能,它只会在选择 1 个单元格时起作用)。>
有几种方法可以防止多单元格选择发生错误,想到的一些事情是;
CellCount
然后检查您的 Worksheet_Change
事件 - If CellCount > 1 Then Exit Sub
以防止代码运行。Target
调整 Set Target = Me.Range(Target.Resize(1, 1).Address(False, False))
范围的大小,这会将 Target.Address
更改为所选单元格的左上角单元格。这本身不会移动或更改工作表上的实际选择,但可用于通知用户该单元格将用于代替所选的多单元格等。