我对编码比较陌生,但之前曾在VBA工作过(很多人以前......)
当用户按下按钮并激活宏时,会出现一个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
答案 0 :(得分: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
首先看起来不错......只需要改进rnd-part。不过,这不是问题的一部分;)
修改强>
对于“不重复”,我建议使用这样的集合:
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
如果您还有任何疑问,请询问:)