2

我可以使用什么最简单的公式来随机选择 A 列中与给定 B 值相关联的值。所以在下表中,我希望随机选择一个 B = 3 的 A。所以我在第 1 行 (5.4) 和第 3 行 (4.2) 之间随机选择。请注意,此表可以任意大。

    A     B

1   5.4   3          
2   2.3   1
3   4.2   3
4   9.2   2
    ...   ...
4

2 回答 2

1

从概念上讲,您可以通过多种方式做到这一点,但这里有一个(VBA),您可以使用一系列可能的选择,然后从该列表中获取一个随机元素:

  1. 创建一个带有范围和搜索值的 udf
  2. 遍历该行,如果它等于您的搜索值,则获取单元格偏移量 -1 中的值并将其存储在一个数组中
  3. 完成后,您将获得所有可能答案的数组。使用 randbetween 函数并为其指定数组的 lbound 和 ubound。
  4. 返回 i 元素,其中 i 是它选择的随机数。

更新:这是一个代码示例,它遍历您指定的数字的范围,如果找到它,它将 A 列值添加到可能结果的数组中。然后生成一个随机数并用于从该列表中返回一个随机值。

Function GetRand(ByVal cell_range As Range, ByVal criteria As Double) As Double

Dim cell As Range
Dim rNum As Long
Dim i As Long
Dim possibleChoices() As Double
ReDim possibleChoices(1 To cell_range.Count)

i = 1
For Each cell In cell_range
    If cell.Value = criteria Then
        possibleChoices(i) = cell.Offset(0, -1).Value
        i = i + 1
    End If
Next

rNum = Application.WorksheetFunction.RandBetween(1, i - 1)
GetRand = possibleChoices(rNum)

End Function

优化:这是相同功能的更灵活版本。它需要 3 个参数 - 您想要查看的范围、您想要查找的内容以及您想要从中获得随机结果的单元格的偏移值。它还使用变体,因此您可以搜索文本或数字。所以在你的情况下,你会写:

=GetRand(B1:B5, 3, -1)

这是代码:

Function GetRand(ByVal cell_range As Range, _
                 ByVal criteria As Variant, _
                 ByVal col_offset As Long) As Variant

Application.ScreenUpdating = False
Dim cell As Range
Dim rNum As Long
Dim i As Long
Dim possibleChoices() As Variant
ReDim possibleChoices(1 To cell_range.Count)

i = 1
For Each cell In cell_range
    If cell.Value = criteria Then
        possibleChoices(i) = cell.offset(0, col_offset).Value
        i = i + 1
    End If
Next

rNum = Application.WorksheetFunction.RandBetween(1, i - 1)

GetRand = possibleChoices(rNum)
Application.ScreenUpdating = True

End Function
于 2011-08-03T23:25:18.183 回答
1

我知道的老问题......但如果你仍然感兴趣,这里有一个假设数据的公式解决方案A2:B10

=INDEX(A2:A10,SMALL(IF(B2:B10=3,ROW(A2:A10)-ROW(A2)+1),RANDBETWEEN(1,COUNTIF(B2:B10,3))))

返回#NUM!如果 B2:B10 中没有 3 则出错.....或包含在 IFERROR 中以在这种情况下返回您选择的文本....

于 2012-01-04T16:28:30.620 回答