2010-04-07 31 views
0

我試圖創建一個列表,每次單擊按鈕時都會添加一行新的數據。我點擊後分配到按鈕下面的代碼:使用VBA按鈕單擊填充新行

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 

此代碼工作正常,但我想它填寫以下,而不是下一行的每個按鈕被點擊時覆蓋在同一行的。我知道我必須迭代「Range(」A2「)。select」部分,例如「Range(」A2「)。select」 - >「Range(」B2「)。select」..但我不知道如何在VBA for Excel中執行此操作。這就是爲什麼我問你的人; )。

感謝,

回答

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 
+0

這就是我的想法,但這段代碼並沒有解決我的問題(它重複寫同一行)。我想我需要變量「行」是持久的,以便在點擊按鈕後存儲行號。就像這樣,只要運行代碼,變量「i」就被初始化爲0。我不知道如何讓「Row」變量持久化。有任何想法嗎?謝謝。 – AME 2010-04-07 01:50:38

+0

啊!這裏:現在通過查看A列並返回下一個空白行,現在總是添加到工作表的末尾。 – 2010-04-07 03:51:45

+0

謝謝你完美的作品! – AME 2010-04-07 06:09:18