EXCEL公式 VBA 隨機生成不重複值

宏代碼

Sub 不重複的值()
Dim arr(1 To 100000, 1 To 1), dic
Set dic = CreateObject("scripting.dictionary")
Do Until i = 100000
   tmp = Format(Int(Rnd() * 100000) + 1, 0)
   If Not dic.exists(tmp) Then
      i = i + 1
      dic.Add tmp, i
      arr(i, 1) = tmp
   End If
Loop
[a1].Resize(i, 1) = arr
End Sub

自定義函數
Function NoSame(t As Long) As Variant
'需要幾個數字,t就爲幾
'比如 =NoSame(100)
'但是要選擇100個單元格,而且是一列的
'比如選擇A1:A100,輸入 =NoSame(100),然後按CTRL+SHIFT+ENTER完成公式
Dim dic, arr
ReDim arr(1 To t, 1 To 1)
Set dic = CreateObject("scripting.dictionary")
Do Until i = t
'Randomize
   tmp = Format(Int(Rnd() * t) + 1, 0)
   If Not dic.exists(tmp) Then
      i = i + 1
      dic.Add tmp, i
      arr(i, 1) = tmp
   End If
Loop
NoSame = arr
End Function
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章