我正在尝试编写一个 VBA 公式,其中如果填充了 A 列中最后使用的行之后的单元格,则公式将出现在新填充的行的 C 列中。我的问题是,下面的代码仅在填充 A 列中的新行后才填充代码,但随后该值被删除。我需要在填充 A 列时填充 C 列。以下是我到目前为止所拥有的。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Dim cell As Range
Dim lastRow As Long
' Define the range of rows to check
lastRow = Me.Cells(Me.Rows.Count, "A").End(xlUp).Row
' Turn off events to prevent infinite loop
Application.EnableEvents = False
' Check if any cell within the defined range has changed
If Not Intersect(Target, Me.Range("A" & lastRow + 1)) Is Nothing Then
If Target.Row = lastRow + 1 Then
Me.Cells(lastRow + 1, "C").formula = "=XLOOKUP($A" & lastRow + 1 & ",Inventario!$A:$A,Inventario!C:C)"
End If
End If
' Turn on events
Application.EnableEvents = True
End Sub
提前感谢您的所有帮助!
XLOOKUP
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lcell As Range: Set lcell = Me.Cells(Me.Rows.Count, "A").End(xlUp)
If Intersect(lcell, Target) Is Nothing Then Exit Sub
Application.EnableEvents = False
lcell.EntireRow.Columns("C").Formula = "=XLOOKUP(" _
& lcell.Address(0) & ",Inventario!A:A,Inventario!C:C)"
Application.EnableEvents = True
End Sub