以下的編碼可列出最多 13 個數字或文字的排列 (Permutations)
Sub PermutationsFromRange()
Dim DestRange As Object
Dim PermString As Variant
Dim NewPerm As String
Dim SepChar As String
Dim NumOfElements As Integer
Dim NumOfPerm As Double
Dim Factorial(1 To 13)
Dim Counter1 As Long
Dim Counter2 As Long
Dim Rotate As Integer
Dim Dummy
' 最多 13 個元素
PermString = Range("A1:A3")
SepChar = ","
NumOfElements = UBound(PermString)
NumOfPerm = Application.Fact(NumOfElements)
For Counter1 = 1 To NumOfElements
Factorial(Counter1) = Application.Fact(NumOfElements - Counter1)
Next Counter1
Worksheets.Add
Set DestRange = Range("a1")
For Counter1 = 1 To NumOfElements
NewPerm = NewPerm & PermString(Counter1, 1) & SepChar
Next Counter1
DestRange.Value = Left(NewPerm, Len(NewPerm) - Len(SepChar))
For Counter1 = 2 To NumOfPerm
NewPerm = ""
If Counter1 / 2 = Int(Counter1 / 2) Then
Rotate = NumOfElements - 1
Else
For Counter2 = 1 To NumOfElements - 2
If Counter1 Mod Factorial(Counter2) = 1 Then
Rotate = Counter2
Exit For
End If
Next Counter2
End If
For Counter2 = 1 To Int((NumOfElements - Rotate + 1) / 2)
Dummy = PermString(Rotate + Counter2 - 1, 1)
PermString(Rotate + Counter2 - 1, 1) = PermString(NumOfElements - Counter2 + 1, 1)
PermString(NumOfElements - Counter2 + 1, 1) = Dummy
Next Counter2
For Counter2 = 1 To NumOfElements
NewPerm = NewPerm & PermString(Counter2, 1) & SepChar
Next Counter2
DestRange.Offset(Counter1 - 1) = Left(NewPerm, Len(NewPerm) - Len(SepChar))
Next Counter1
Set DestRange = Nothing
End Sub
EUfbkR3W.zip
(8.46 KB, 下载次数: 97)
[此贴子已经被作者于2004-12-22 14:01:28编辑过] |