1

我有代码可以防止一次更改多个单元格。但是,它允许一次删除多个单元格。下面是我正在使用的代码,它运行良好。

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

我要添加的是当数据被删除时,我希望它检查正在从哪些列中删除数据。如果任何一列满足要求,那么我还需要删除另一列中等效行中的数据。

这是我正在尝试做的一个例子。我需要检查 2 列,它们是 G 和 H。如果从这 2 列中的任何一个中删除数据,那么我也希望删除列 I。假设我选择 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
4

1 回答 1

1

我已经修改了您的代码以确定 G 或 H 列是否在目标中。如果是这样,则 I 列中的相应行也将被清除。我还删除了循环部分中不必要的If测试。ElseFor

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
于 2013-06-27T04:27:18.267 回答