I've been messing around with VBA in Excel a bit recently; and as a small project for myself, I'm trying to create a "draw names from a hat" sort of macro.

I began by generating a random number, and then choosing which entry from a Table (i.e. ListObject) would be selected using a case statement. The problem with this is that it only works of the number of Table entries is always the same.

So my question (probably a ridiculous one) is: is it possible at all to generate a dynamic 'Select Case' block, where the number of cases on the block is based on the number of entries in the Table?

Thanks.

-Sean

Edit: To clarify: what I am trying to do, exactly, is this:

I generate a random number, i, from 1 to n=10*(number of Table entries). After this, I want to display, in a cell, one of the table entries based on the random number.

Ideally, the code would work similarly to this:

if i = 1 to 10 then choose event 1
if i = 11 to 20 then choose event 2
if i = 21 to 30 then choose event 3
...
if i = (n-9) to n then choose event (n/10)

I hope this helps to clarify the goal of the code.

有帮助吗?

解决方案

From our comments here is something you can use:

Sub random()
    Dim used_rows As Integer
    Dim random As Integer
    Dim cell_array() As Integer
    used_rows = Sheet1.UsedRange.Rows.Count
    ReDim cell_array(used_rows)
    For i = 1 To used_rows
        cell_array(i - 1) = Cells(i, 1)
    Next
    random = Int(Rnd * (used_rows))
    MsgBox cell_array(random)
End Sub

You can go ahead and change MsgBox to whatever you like, or set like Cell(1,4).Value = cell_array(random), or however you'd like to proceed. It will be based off the number of rows used. Though depending on how you implement your spreadsheet the code might have to be changed a bit.

Here's the update code from the suggestions from the comments. Also remember to use Randomize() in your form initialization or WorkBook Open functions.

Sub random()
    Dim used_rows As Integer
    Dim random As Integer
    'Multiple ways to get the row count, this is just a simple one which will work for most implementations
    used_rows = Sheet1.UsedRange.Rows.Count
    random = Int(Rnd * (used_rows)) 
    'I use the variable only for the reason that you might want to reference it later
    MsgBox Cells(random, 1)
End Sub

其他提示

This assumes that by "table" you mean "Table with a capital T", known in VBA as a ListObject:

Sub PickRandomTens()
Dim lo As Excel.ListObject
Dim ListRowsCount As Long
Dim RandomNumber As Long
Dim ListEvent As String
Dim Tens As Long

Set lo = ActiveSheet.ListObjects(1)
ListRowsCount = lo.DataBodyRange.Rows.Count
RandomNumber = Application.WorksheetFunction.RandBetween(10, ListRowsCount * 10)
ListEvent = lo.ListColumns("Data Column").DataBodyRange.Cells(Int(RandomNumber / 10))
MsgBox "Random number: " & RandomNumber & vbCrLf & _
       "Event: " & ListEvent
End Sub
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top