是否有可能根据表中的条目数来将案例添加到Select Case中?

最近我一直在使用Excel中的VBA, 作为我自己的一个小项目,我试图创造一个“从帽子上画出名字”的那种macros观。

我从生成一个随机数开始,然后从一个表(即ListObject)中select使用case语句select哪个条目。 与此相关的问题是,它只能工作的条目数总是相同的。

所以我的问题(可能是一个荒谬的)是:是否有可能生成一个dynamic的“select案例”块,块的情况下的数量是基于表中的条目数?

谢谢。

-Sean

编辑:澄清:我正在试图做的,正是这样的:

我生成一个随机数,我从1到n = 10 *(表项的数量)。 之后,我想在单元格中显示基于随机数的表项之一。

理想情况下,代码的工作方式与此类似:

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) 

我希望这有助于澄清代码的目标。

从我们的评论这里是你可以使用的东西:

 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 

您可以继续,将MsgBox更改为任何您喜欢的内容,或者设置为Cell(1,4).Value = cell_array(random),或者您想继续。 它将基于所使用的行数。 尽pipe取决于您如何实现电子表格,但代码可能需要稍微更改一下。

以下是来自评论build议的更新代码。 还要记住在表单初始化或WorkBook Open函数中使用Randomize()。

 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 

这里假定“table”的意思是“Table with a capital T”,在VBA中被称为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