使用 VBA
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, i As Long
Dim ar As Variant
Dim varrRandomNumberList As Variant
Set ws = Sheets("Sheet1")
With ws
lRow = .Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lRow
ar = .Range("A" & i & ":D" & i)
varrRandomNumberList = UniqueRandomNumbers(4, 1, 4)
.Range("A" & i).Value = ar(1, varrRandomNumberList(1))
.Range("B" & i).Value = ar(1, varrRandomNumberList(2))
.Range("C" & i).Value = ar(1, varrRandomNumberList(3))
.Range("D" & i).Value = ar(1, varrRandomNumberList(4))
Next i
End With
End Sub
'~~> Function picked from
'~~> http://www.exceltip.com/st/Return_random_numbers_using_VBA_in_Microsoft_Excel/531.html
Function UniqueRandomNumbers(NumCount As Long, LLimit As Long, ULimit As Long) As Variant
'~~> Creates an array with NumCount unique long random numbers in the range
'~~> LLimit - ULimit (including)
Dim RandColl As Collection, i As Long, varTemp() As Long
UniqueRandomNumbers = False
If NumCount < 1 Then Exit Function
If LLimit > ULimit Then Exit Function
If NumCount > (ULimit - LLimit + 1) Then Exit Function
Set RandColl = New Collection
Randomize
Do
On Error Resume Next
i = CLng(Rnd * (ULimit - LLimit) + LLimit)
RandColl.Add i, CStr(i)
On Error GoTo 0
Loop Until RandColl.Count = NumCount
ReDim varTemp(1 To NumCount)
For i = 1 To NumCount
varTemp(i) = RandColl(i)
Next i
Set RandColl = Nothing
UniqueRandomNumbers = varTemp
Erase varTemp
End Function
快照