如果列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
答案 0 :(得分:1)
假设“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
答案 1 :(得分:1)
您可以在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