我想在添加行时在列L到R中添加以下公式。到目前为止,这就是我所拥有的。
但我似乎无法弄清楚如何确保只在添加行时才会出现此宏,并且我不希望它运行到最后一行但仅针对添加的最新行。 谁能帮我这个。我仍然是VBA的新手,虽然我环顾四周如何做到这一点,但我无法捕捉到有助于我仅在添加的行上添加此公式的信息。 谢谢你的帮助
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
For i = 2 To LastRow
Range("L" & i).Value = "=NETWORKDAYS(RC[-8],RC[-7],Holidays)"
Range("M" & i).Value = "=NETWORKDAYS(RC[-8],RC[-7],Holidays)"
Range("N" & i).Value = "=NETWORKDAYS(RC[-8],RC[-7],Holidays)"
Range("O" & i).Value = "=NETWORKDAYS(RC[-8],RC[-7],Holidays)"
Range("P" & i).Value = "=NETWORKDAYS(RC[-8],RC[-7],Holidays)"
Range("Q" & i).Value = "=NETWORKDAYS(RC[-8],RC[-7],Holidays)"
Range("R" & i).Value = "=NETWORKDAYS(RC[-8],RC[-7],Holidays)"
Next
End Sub
答案 0 :(得分:0)
有几种方法可以做到这一点(可能还有其他方法)。
测试Target
范围以查看其Address
是否为完整行:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim test As Range
Set test = Target.EntireRow
If test.Address = Target.Address Then
Debug.Print "Entire row changed"
End If
End Sub
测试Target
范围的列数,看它是否包含每一列:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Columns.Count = Me.Columns.Count Then
Debug.Print "Entire row changed"
End If
End Sub
手动跟踪最后一行并与缓存值进行比较:
Private previousBottom As Long '<--Worksheet level variable.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim bottom As Long
bottom = Me.Cells(Me.Rows.Count, 1).End(xlUp).Row
If bottom <> previousBottom Then
previousBottom = bottom
Debug.Print "Row inserted or deleted."
End If
End Sub