假设:excel中有一组数为:25,33,45,4584,564,5646,64,89,654,6546,61561,6543,6464
请问有什么办法知道其中的哪几个数和为12546? 请宏高手帮忙解决。谢谢
------解决方案--------------------------------------------------------
在VBA中实现了:
- VB code
Option ExplicitSub Combine(a() As Long, ByVal n As Integer, ByVal m As Integer, b() As Long, ByVal L As Integer, ByRef c As Collection) Dim i As Integer Dim j As Integer For i = n To m Step -1 b(m - 1) = i - 1 If m > 1 Then Combine a, i - 1, m - 1, b, L, c Else If c Is Nothing Then Set c = New Collection End If Dim s() As Long ReDim s(0 To L - 1) Dim k As Integer k = 0 For j = L - 1 To 0 Step -1 s(k) = a(b(j)) k = k + 1 Next j c.Add (s) End If Next iEnd SubPrivate Function GetSum(ByRef arr() As Long) As Long Dim i As Integer Dim sum As Long For i = 0 To UBound(arr) sum = sum + arr(i) Next GetSum = sumEnd FunctionPrivate Sub Command1_click() Dim i As Integer Dim j As Integer Dim k As Integer Dim c As Collection Dim hasSoluction As Boolean Dim index As Integer ReDim a(0 To 12) As Long, b(0 To 12) As Long a(0) = 25 a(1) = 33 a(2) = 45 a(3) = 4584 a(4) = 564 a(5) = 5646 a(6) = 64 a(7) = 89 a(8) = 654 a(9) = 6546 a(10) = 61561 a(11) = 6543 a(12) = 6464 index = 1 For i = 1 To 12 Set c = New Collection Call Combine(a, 12, i, b, i, c) For j = 0 To c.Count - 1 Dim s() As Long s = c(j + 1) 'Me.Text1.Text = Me.Text1.Text & GetSum(s) & vbCrLf If GetSum(s) = 12546 Then hasSoluction = True For k = 0 To UBound(s) Sheet2.Cells(index, k + 1) = s(k) Next End If Next j Next i If Not hasSoluction Then MsgBox "无解" End IfEnd Sub