2016-03-05 158 views
0

我是比較新的編碼,但在VBA之前工作過(很久以前...)Excel宏循環,並追加

當用戶按下按鈕,啓動宏,一個的InputBox,並詢問然後,要求玩家購買彩票的數量,然後從1-24中隨機分配三個數字(按升序顯示,不重複,就像我們的樂透,我還沒有已經能夠編碼這個條件;我會在稍後...)

在初始代碼運行後,它輸入所有數據行2通過票+1的數量,這一切迄今爲止工作;但是,我希望能夠在每次運行宏時追加到當前列表(每次按下按鈕)。我嘗試了幾種不同的方式來做到這一點,但沒有成功。請幫忙。我究竟做錯了什麼?

Sub New_Entry() 
    Dim strPlayer As String, strTick As Integer, i As Integer, j As Integer 

    strPlayer = InputBox("Input Player Name") 
    strTick = InputBox("How many tickets?") 

' For i = 2 To strTick + 1 <-- This works for a single loop that does not append to the previous data 
' For i = Range(i & Range(i & Rows.Count).End(xlUp).Row + 1) To Range(i & Range(i & Rows.Count).End(xlUp) + strTick) <-- This does not work, at all. 

     For j = 1 To 4 
      Cells(i, 1).Value = strPlayer 
      Cells(i, j).Value = Int((24 - 1 + 1) * Rnd + 1) 
     Next j 
    Next i 

End Sub 

' Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1).Value = strPlayer 
' Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1).Value = i 
' Range("C" & Range("C" & Rows.Count).End(xlUp).Row + 1).Value = j 

回答

1

如果j從1到4,它會覆蓋玩家姓名(而在第二循環中有它,玩家也將被打印4次)......首先,j應該只從2走到4 ...其次Cells(i, 1).Value = strPlayer應該在第二個循環之外...第三:你已經有了追加部分。
剛剛合併在一起的一切,你已經有了,我得到這個:

Sub New_Entry() 
    Dim strPlayer As String, strTick As Integer, i As Integer, j As Integer 
    strPlayer = InputBox("Input Player Name") 
    strTick = InputBox("How many tickets?") 
    i = Cells(Rows.Count, 1).End(xlUp).Row + 1 
    For i = i To i + strTick - 1 
    Cells(i, 1).Value = strPlayer 
    For j = 2 To 4 
     Cells(i, j).Value = Int((24 - 1 + 1) * Rnd + 1) 
    Next j 
    Next i 
End Sub 

enter image description here

不擺在首位看錯了......只是RND部分有待提高。儘管如此,問題是wasnt一部分;)

編輯
對於「不重複」我建議使用集合是這樣的:

Sub New_Entry() 
    Dim strPlayer As String, strTick As Integer, i As Integer, j As Integer 
    Dim ColA As New Collection 
    strPlayer = InputBox("Input Player Name") 
    strTick = InputBox("How many tickets?") 
    i = Cells(Rows.Count, 1).End(xlUp).Row + 1 
    For i = i To i + strTick - 1 
    Cells(i, 1).Value = strPlayer 
    For j = 1 To 24 
     ColA.Add j 
    Next 
    While ColA.Count > 3 
     ColA.Remove Int(ColA.Count * Rnd + 1) 
    Wend 
    For j = 2 To 4 
     Cells(i, j).Value = ColA(1) 
     ColA.Remove 1 
    Next j 
    Next i 
End Sub 

如果您還有任何問題,只是問:)

+0

@JacobHooper ...添加了unique-sorted-numbers部分;) –