简体   繁体   English

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

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

Whenever I change a value (choose some value from data validation list) in column G, it should clear the cell in the next column H.每当我更改 G 列中的值(从数据验证列表中选择一些值)时,它应该清除下一列 H 中的单元格。

So when I choose value in G4, value in H4 will be deleted.所以当我在 G4 中选择 value 时,H4 中的 value 将被删除。 When I choose value in G5, tha same would happen with H5.当我在 G5 中选择 value 时,H5 也会发生同样的情况。

I tried this, but not working:我试过这个,但不起作用:

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

No need of iteration for such a task.这样的任务不需要迭代。 Since, the cell value is changed by selecting from a drop down validation list, multiple changes are not possible.由于通过从下拉验证列表中进行选择来更改单元格值,因此无法进行多次更改。 For such a case, the code simple exists:对于这种情况,存在简单的代码:

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

This can be done like this:这可以像这样完成:

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