Excelmacros循环和追加

我是相对较新的编码,但曾在VBA(许多月前…)

当用户按下button并激活macros时,出现一个input框并询问玩家名称,然后询问玩家购买的彩票的数量,然后随机化1-3个中的三个数字(出现在升序,不要重复,就像我们的乐透,我还没有能够编码这个条件,我会到达那里…)

初始代码运行后,它通过票数+ 1input所有的数据行2,这一切都工作到目前为止; 但是,我希望能够每次运行macros时追加到当前列表(每次按下button)。 我尝试了几种不同的方式来做这件事,但都没有成功。 请帮忙。 我究竟做错了什么?

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 

如果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 

在这里输入图像说明

首先看起来不错,只是需要改进的部分。 不过,这不是问题的一部分;)

编辑
对于“不重复”,我build议使用这样的集合:

 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 

如果你还有任何问题,只要问:)