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



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

所以当我选择G4中的值时,H4中的值将被删除。当我在G5中选择值时,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

最新更新