简体   繁体   English

Excel VBA清除一个单元格中的内容(如果另一个为空)

[英]Excel VBA clear content in one cell if another is empty

Below code is used to add information in specified cells if there is value in Column A, same row. 如果A列的同一行中有值,则下面的代码用于在指定的单元格中添加信息。 Everything works except I want to clear the value in Column E for the same row if I delete the value in column A. 一切正常,除了如果要删除A列中的值,我想清除同一行中E列中的值。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Me.Range("A:A")) Is Nothing Then Exit Sub
    Application.EnableEvents = False             'to prevent endless loop
    On Error GoTo Finalize                       'to re-enable the events

    For Each columnAcell In Target.Cells
        columnAcell.Offset(0, 3) = Mid(columnAcell, 2, 3)
    Next

    Dim w1 As Worksheet, w2 As Worksheet
    Dim c As Range, FR As Variant

    Application.ScreenUpdating = False

    Set w1 = Workbooks("Excel VBA Test.xlsm").Worksheets("AP_Input")
    Set w2 = Workbooks("Excel VBA Test.xlsm").Worksheets("Datakom")

    For Each c In w1.Range("D2", w1.Range("D" & Rows.Count).End(xlUp))
        FR = Application.Match(c, w2.Columns("A"), 0)
        If IsNumeric(FR) Then c.Offset(, 1).Value = w2.Range("B" & FR).Value
    Next c

    Finalize:
    Application.EnableEvents = True
End Sub

Assuming the "columnAcell" is to represent a range of cells in the column A, how about redoing the first loop as follows? 假设“ columnAcell”代表列A中的一系列单元格,那么如何如下重做第一个循环呢?

For Each columnAcell In Target.Cells
    columnAcell.Offset(0, 3) = Mid(columnAcell, 2, 3)
    If ISEMPTY(columnAcell.value) Then columnAcell.Offset(0, 4).ClearContents
Next

You may add an IF condition within the For Loop to check if a cell in column A is empty like this... 您可以在For循环中添加IF条件,以检查A列中的单元格是否为空……

For Each columnAcell In Target.Cells
    If columnAcell <> "" Then
        columnAcell.Offset(0, 3) = Mid(columnAcell, 2, 3)
    Else    'if column A cell is empty
        columnAcell.Offset(0, 4) = ""   'Clear the cell content in column E on same row
    End If
Next

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

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