使用VBA按钮单击填充新行

时间:2010-04-07 01:27:19

标签: excel-vba vba excel

我正在尝试创建一个列表,每次单击一个按钮时都会添加一行新数据。单击时,我将以下代码分配给按钮:

    PurchaseDate = InputBox("Enter Purchase Date:")
    Sheets("TrackRecord").Select
    i = 0
    Row = i + 1
    Range("A2").Select
    ActiveCell.FormulaR1C1 = Row
    Range("B2").Select
    ActiveCell.FormulaR1C1 = "=Dashboard!R26C4*(1/Dashboard!R26C12)"
    Range("C2").Select
    ActiveCell.FormulaR1C1 = "=Dashboard!R26C2"
    Range("D2").Select
    ActiveCell.FormulaR1C1 = PurchaseDate
    Range("E2").Select
    ActiveCell.FormulaR1C1 = "=Dashboard!R26C8 + R2C4"
    Range("F2").Select
    ActiveCell.FormulaR1C1 = "=Waterfall!R[8]C[5]"
    Range("F2").Select
    Selection.AutoFill Destination:=Range("F2:I2"), Type:=xlFillDefault
    Range("F2:I2").Select
End Sub

此代码工作正常,但我希望它填充下面的下一行,而不是每次单击按钮时覆盖相同的行。我知道我必须遍历“范围(”A2“)。选择”部分,例如“范围(”A2“)。选择” - > “范围(”B2“)。选择”..但我不知道如何在VBA for Excel中执行此操作。这就是我问你们的原因; )。

谢谢,

1 个答案:

答案 0 :(得分:1)

如果你想关闭excel并再次打开它,你想要保留下一行,最好每次都找到最后一行。

 Dim Row As Long

    Row = GetNextRow(Sheets("TrackRecord"), "A") 

    PurchaseDate = InputBox("Enter Purchase Date:") 

    Sheets("TrackRecord").Select 

    Range("A" & Row).Select 
    ActiveCell.FormulaR1C1 = Row 
    Range("B" & Row).Select 
    ActiveCell.FormulaR1C1 = "=Dashboard!R26C4*(1/Dashboard!R26C12)" 
    Range("C" & Row).Select 
    ActiveCell.FormulaR1C1 = "=Dashboard!R26C2" 
    Range("D" & Row).Select 
    ActiveCell.FormulaR1C1 = PurchaseDate 
    Range("E" & Row).Select 
    ActiveCell.FormulaR1C1 = "=Dashboard!R26C8 + R2C4" 
    Range("F" & Row).Select 
    ActiveCell.FormulaR1C1 = "=Waterfall!R[8]C[5]" 
    Range("F" & Row).Select 
    Selection.AutoFill Destination:=Range("F" & Row & ":I" & Row), Type:=xlFillDefault 
    Range("F" & Row & ":I" & Row).Select 
End Sub 


Private Function GetNextRow(sheet As Worksheet, column As String) As Long

    'Look for the first empty row in the specified column

    Dim Row As Long

    For Row = 1 To 65535
        If sheet.Range(column & Row).Formula = "" Then
            GetNextRow = Row
            Exit For
        End If
    Next Row

End Function