在excel中创建一个数字的所有可能组合

时间:2017-09-29 15:49:57

标签: excel-formula

我想在excel中输入一个数字并给我4位数的组合。我可以这样做吗?像这样我输入8并给我

  

2 2 2 2
  2 3 2 1
  5 1 1 1
  等

1 个答案:

答案 0 :(得分:2)

运行子phoniX()

Sub phoniX()
    Dim N As Long, ary(1 To 4) As Long

    N = Application.InputBox(prompt:="enter value", Type:=1)
    xxx = 1

    For i = 0 To N
        For J = 0 To N
            For k = 0 To N
                For l = 0 To N
                    If i + J + k + l = N Then
                        ary(1) = i
                        ary(2) = J
                        ary(3) = k
                        ary(4) = l
                        Call LittleSort(ary())
                        Cells(xxx, 1).Value = "'" & ary(1) & ary(2) & ary(3) & ary(4)
                        xxx = xxx + 1
                    End If
                Next l
            Next k
        Next J
    Next i

    Range("A:A").RemoveDuplicates Columns:=1, Header:=xlNo
End Sub

Public Sub LittleSort(ByRef InOut)

    Dim i As Long, J As Long, Low As Long
    Dim Hi As Long, Temp As Variant

    Low = LBound(InOut)
    Hi = UBound(InOut)

    J = (Hi - Low + 1) \ 2
    Do While J > 0
        For i = Low To Hi - J
          If InOut(i) > InOut(i + J) Then
            Temp = InOut(i)
            InOut(i) = InOut(i + J)
            InOut(i + J) = Temp
          End If
        Next i
        For i = Hi - J To Low Step -1
          If InOut(i) > InOut(i + J) Then
            Temp = InOut(i)
            InOut(i) = InOut(i + J)
            InOut(i + J) = Temp
          End If
        Next i
        J = J \ 2
    Loop
End Sub

生产:

enter image description here