介紹如在 Excel VBA 中使用 Rnd
函數產生隨出的亂數。
Rnd
函數
VBA 的 Rnd
函數可以產生介於 0
到 1
的隨機亂數(大於或等於 0
且小於 1
)。
' 產生 0 <= x < 1 的亂數 RandNum = Rnd() MsgBox ("亂數:" & RandNum)

0
到 1
之間的隨機亂數
初始化隨機亂數
在實務上為了讓亂數接近隨機,在使用 Rnd
產生亂數之前,可先呼叫 Randomize
函數,以目前時間來設定亂數種子,初始化亂數,確保每次執行程式都會產生不同的亂數:
' 以時間初始化亂數 Randomize() ' 產生亂數 RandNum = Rnd()
產生隨機整數亂數
若要產生隨機的整數,可以用 Rnd
產生浮點數之後,再經過簡單的轉換即可。
' 設定整數亂數範圍 Min = 3 Max = 9 ' 產生 Min <= x <= Max 的亂數 RandNum = Int((Max - Min + 1) * Rnd() + Min) MsgBox ("亂數:" & RandNum)


產生隨機字串
若需要產生隨機的文字,可以自行定義一個產生隨機字串的函數:
' 產生長度為 n 的隨機字串 Function RandString(n As Long) As String Dim i As Long, j As Long, m As Long, s As String, pool As String ' 設定可用的字元 pool = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" m = Len(pool) For i = 1 To n j = 1 + Int(m * Rnd()) s = s & Mid(pool, j, 1) Next i RandString = s End Function
在這個自訂函數中,pool
這個變數是用來設定可用的字元,可以自由增加或減少裡面的字元。接著使用這個自訂的函數即可產生任意長度的隨機字串:
Sub Run() ' 產生長度為 20 的隨機字串 RandStr = RandString(20) MsgBox ("隨機字串:" & RandStr) End Sub

