简体   繁体   中英

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.

So when I choose value in G4, value in H4 will be deleted. When I choose value in G5, tha same would happen with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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