我的代码可以防止一次更改多个单元格。但是,它允许一次删除多个单元格。下面是我正在使用的代码,它运行良好。
Dim vClear As Variant
Dim vData As Variant
'This prevents more than one cell from being changed at once.
'If more than one cell is changed then validation checks will not work.
If Target.Cells.Count > 1 Then
vData = Target.Formula
For Each vClear In vData
If vClear <> "" Then 'If data is only deleted then more than one cell can be changed.
MsgBox "Change only one cell at a time", , "Too Many Changes!"
Application.Undo
Exit For
End If
Next
End If
我想要添加的是当数据被删除时我希望它检查哪些列数据正在被删除。如果任何列满足要求,那么我还需要删除另一列中等效行中的数据。
这是我想要做的一个例子。有两列我需要检查,它们是G&amp; H.如果从这两列中的任何一列中删除数据,那么我也希望删除第一列。假设我选择D5的范围:G10并从中删除内容。由于G列是我想要I5的要求之一:I10也被删除了。如果我要删除D5:F10,那么它不会删除列I中的任何内容,因为列G或H都没有被选中。
以下是我正在尝试做的示例代码。我知道下面的代码不可能工作,这只是我想要做的简短摘要,我无法弄清楚如何让变量也检查列。如果有人知道如何做,请告诉我。
Dim vClear As Variant
Dim vData As Variant
'This prevents more than one cell from being changed at once.
'If more than one cell is changed then validation checks will not work.
If Target.Cells.Count > 1 Then
vData = Target.Formula
For Each vClear In vData
If vClear <> "" Then 'If data is only deleted then more than one cell can be changed.
MsgBox "Change only one cell at a time", , "Too Many Changes!"
Application.Undo
Exit For
Else
If vClear = "" Then
If vClear.Column = 7 Or vClear.Column = 8 Then
ActiveSheet.Cells(vClear.Row, 9) = ""
End If
End If
End If
Next
End If
答案 0 :(得分:1)
我修改了您的代码以确定G或H列是否在Target中。如果是,则也清除列I中的相应行。我还在If
循环的Else
部分删除了不必要的For
测试。
Dim vClear As Variant
Dim vData As Variant
Dim firstRow As Long
Dim lastRow As Long
'This prevents more than one cell from being changed at once.
'If more than one cell is changed then validation checks will not work.
If Target.Cells.Count > 1 Then
vData = Target.Formula
For Each vClear In vData
If vClear <> "" Then 'If data is only deleted then more than one cell can be changed.
MsgBox "Change only one cell at a time", , "Too Many Changes!"
Application.Undo
Exit For
Else
' if the target includes columns G or H, we also clear column i
If Not Intersect(Target, Columns("G:H")) Is Nothing Then
' get the first row in the target range
firstRow = Target.Rows(1).Row
' get the last row in the target range
lastRow = firstRow + Target.Rows.Count - 1
' clear contents of corresponding rows in column i
ActiveSheet.Range(Cells(firstRow, 9), Cells(lastRow, 9)).ClearContents
End If
End If
Next
End If