1、如下图A列是某班级19位同学的姓名,现在我们想要用vba为这19名同学随机安排座位号。
2、选中B2:B20单元格区域,然后同时按下Alt+F11
3、点击sheet1,然后在右边空白区录入vba代码,接着按下F5运行代码
4、录入1作为最小随机数,然后点击【确定】
5、接着在最大随机数字选项内录入19,点击【确定】
6、接着点击【确定】即可完成
7、完成效果如下图,最后跟大家分享一下本文这里所使用的vba代码。如果需要Excel vba 代做 请百度方方格子Sub 生成不重复的随机数() 晦倘佳鳎On Error Resume Next Dim count As Long, needCount As Long Dim rn As Range Dim max, min, unit As Double Dim bRepeat As Boolean Dim d As Object Dim i, v count = Selection.Cells.count If count > 10000 Then MsgBox "请不要选择超过10000个单元格!" Exit Sub End If min = Application.InputBox(prompt:="随机最小数字", Type:=1, Default:="0") If Not IsNumeric(min) Then Exit Sub 'false 不够准确,0也是false max = Application.InputBox(prompt:="随机最大数字", Type:=1, Default:="100") If Not IsNumeric(max) Then Exit Sub unit = Application.InputBox(prompt:="随机数的精确单位,如精确到1、精确到0.2 等等", Type:=1, Default:="1") If Not IsNumeric(unit) Then Exit Sub 'If unit = False Then Exit Sub '--------------------------------------- needCount = Int((max - min + unit) / unit) If count > needCount Then count = needCount '合理个数 'MsgBox "您选择的区域太大,无法生成不重复的随机数! 至多只能选中" & needCount & "个单元格!" 'Exit Sub End If Set d = CreateObject("scripting.dictionary") Randomize Timer For i = 1 To count Do v = Int(Rnd() * Int((max - min + unit) / unit)) * unit + min Loop While d.exists(v) Selection.Cells(i) = v d.Add v, "" Next iEnd Sub