我有3个值(5,4,8),我想在10个单元格之间随机分配它们

时间:2017-09-29 06:12:27

标签: excel excel-vba excel-formula vba

我有10个单元格A1:A10,我有3个值(5,4,8)

我想在A1:A10中随机分发它们,所以10个单元格中只有3个会被填充而另外7个将是空白的

如何制作?

例如: please see the screenshot

please see the other screenshot

3 个答案:

答案 0 :(得分:2)

您还可以使用常规Excel公式实现此目的,以下是您的操作方法:

  • Column A:输入您提到的三个值(5,4,8)和其他7个包含一个空格的单元格

  • Column B:填写此公式=RAND()

  • Column C:填写此fomrula =INDEX($A$2:$A$11,RANK(B2,$B$2:$B$11))

这样做的目的是通过排名返回非重复的随机列表。因此,你必须有其他7个单元格,空格。

请注意我有一个标题行,因此您可能需要稍微调整一下公式以满足您的需要。试着让我知道。

答案 1 :(得分:1)

如果您尝试自动化,可以将以下VBA绑定到命令按钮。 我已经包含了一个链接,指向如何随机化保存数字4,5,8的数组。假设您正在一个名为TargetSheet的工作表中运行。

Option Explicit

Sub AssignNumbers()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim x As Long, i As Long
Dim Arr()

Set wb = ThisWorkbook
Set ws = wb.Sheets("TargetSheet")
Set rng = ws.[A1:A10]

Arr = Array(4, 5, 8)  'You can randomize this array as follows (somewhat irrelevant as assignment is random): _
http://www.cpearson.com/excel/ShuffleArray.aspx

rng.ClearContents

For i = 0 To 2
    'Loop until we find an empty cell to place the value in
    Do
        x = Application.WorksheetFunction.RandBetween(1, 10)
        'Exit the loop as soon as we find a place to put the value
        If IsEmpty(rng.Cells(x, 1).Value) Then Exit Do
    Loop
    'Have found an empty cell - we can now set the value
    rng.Cells(x, 1) = arr(i)
Next i
End Sub

答案 2 :(得分:0)

  1. 制作一个数字从1到10
  2. 的列表(或数组)
  3. 随机化列表的顺序
  4. 在A1:10 *
  5. 中以随机顺序绘制数字
  6. 利润!
  7. *任何不是4,5或8的数字都可以转换为空白单元格

    创建并随机化数组并将其打印到A1:10

    Sub RunShuffle()
        Dim i As Integer
        Dim j As Integer
        Dim MyArray(9) As Variant
    
        'Fill the array with numbers 1 to 10
        For i = LBound(MyArray) To UBound(MyArray)
            MyArray(i) = i + 1
        Next i
    
        'Randomise the order of the array
        ShuffleArrayInPlace MyArray
    
        'Print the randomised array to A1:10
        For j = LBound(MyArray) To UBound(MyArray)
            Sheets(1).Cells(j + 1, "A").Value = MyArray(j)
            If MyArray(j) <> 4 And MyArray(j) <> 5 And MyArray(j) <> 8 Then
                Sheets(1).Cells(j + 1, "A").Value = ""
            End If
        Next j
    
    End Sub
    
    'This Sub shuffles the array given as input
    Sub ShuffleArrayInPlace(InArray() As Variant)
        Dim n As Long
        Dim Temp As Variant
        Dim j As Long
    
        Randomize
        For n = LBound(InArray) To UBound(InArray)
            j = CLng(((UBound(InArray) - n) * Rnd) + n)
            If n <> j Then
                Temp = InArray(n)
                InArray(n) = InArray(j)
                InArray(j) = Temp
            End If
        Next n
    End Sub
    

    随机化代码的来源:CPearson.com