簡體   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