我已经创建了一个脚本,它为我提供了数据选项卡上所做更改的审核日志(我希望提供用户访问权限来进行一次性更改,因此不希望完全锁定和保护选项卡)。
当用户选择一个单元格时,这非常好,但是,当用户选择多个单元格并尝试删除它们或更改它们时,脚本就会崩溃。
哪一行代码是必需的,不允许用户选择多个单元格,或者如果用户选择了多个单元格,则会产生一个弹出窗口,说明他们只能选择一个单元格。
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 ```发布于 2021-05-05 11:14:49
您可以通过检查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 (考虑到如果没有选择任何单元格,则函数不会触发,只有在选择了一个单元格时才能工作)。
有几种方法可以实现防止错误发生的多小区选择,一些事情出现在脑海中;
running.
CellCount,然后签入Worksheet_Change事件- If CellCount > 1 Then Exit Sub,以防止代码
Set Target = Me.Range(Target.Resize(1, 1).Address(False, False))调整Target范围的大小,这将将Target.Address更改为所选单元格的左上角单元格。这本身不会移动或更改工作表上的实际选择,但可用于通知用户此单元格将用于替代所选的多个单元格等。
https://stackoverflow.com/questions/67399754
复制相似问题