繁体   English   中英

VBA,删除行/列值作为增量函数

[英]VBA, deleting row/column values as increment function

每当我更改 G 列中的值(从数据验证列表中选择一些值)时,它应该清除下一列 H 中的单元格。

所以当我在 G4 中选择 value 时,H4 中的 value 将被删除。 当我在 G5 中选择 value 时,H5 也会发生同样的情况。

我试过这个,但不起作用:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 7 Then

For i = 4 To 154 Step 1
    If Target.Address = "$G$i" Then
        Range("Hi").Select
        Selection.ClearContents
    End If
Next i

End If

End Sub

这样的任务不需要迭代。 由于通过从下拉验证列表中进行选择来更改单元格值,因此无法进行多次更改。 对于这种情况,存在简单的代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 7 Then
       If Target.cells.count > 1 Then Exit Sub
       Target.Offset(0, 1).ClearContents
    End If
End Sub

这可以像这样完成:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim oCell As Range
    For Each oCell In Target.Cells  ' You can change many cells at once (i.e. copy-paste or select-delete)
        If oCell.Column = 7 Then ' Is it cell in G:G or any other?
            If oCell.Text <> vbNullString Then ' Has cell any value?
                oCell.Offset(0, 1).ClearContents    ' Clear cell in the next column in this row
            End If
        End If
    Next oCell
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM