20个数2.2,1.3..中选6个数,和为定值18,

1个回答

  • 首先把20个数放到A列,B1放期望值(如18),执行下面的宏,在C列显示结果:

    Sub Macro()

    Dim i,j,k,l,m,n,r As Integer

    Dim s As Single

    r = 1

    s = Cells(1,2)

    Range("c:c") = ""

    For i = 1 To 15

    For j = i + 1 To 16

    For k = j + 1 To 17

    For l = k + 1 To 18

    For m = l + 1 To 19

    For n = m + 1 To 20

    If Cells(i,1) + Cells(j,1) + Cells(k,1) + Cells(l,1) + Cells(m,1) + Cells(n,1) = s Then

    Cells(r,3) = Cells(i,1) & "+" & Cells(j,1) _

    & "+" & Cells(k,1) & "+" & Cells(l,1) & "+" _

    & Cells(m,1) & "+" & Cells(n,1) & "=" & s

    r = r + 1

    End If

    Next n

    Next m

    Next l

    Next k

    Next j

    Next i

    End Sub

    例如:

    A列 B列 C列(执行宏显示结果)

    ---------------------------------------------

    2.5 18 2.5+1.4+6.9+1.6+3+2.6=18

    1.4 2.5+1.4+7.5+1.6+2.6+2.4=18

    9.3 2.5+1.4+7.4+1.1+3+2.6=18

    9.4 2.5+1.4+5+1.6+2.6+4.9=18

    6.9 2.5+1.4+1.6+3+7.1+2.4=18

    7.5 2.5+1.4+1.6+3+6.9+2.6=18

    7.4 2.5+1.4+1.6+7.5+2.6+2.4=18

    1.1 2.5+7.5+1.1+1.6+3+2.3=18

    5 2.5+7.4+1.1+1.6+3+2.4=18

    1.6 2.5+1.1+1.6+3+7.5+2.3=18

    3 2.5+1.1+7.1+2.3+2.6+2.4=18

    7.5 1.4+7.5+1.1+3+2.6+2.4=18

    7.1 1.4+1.1+5+3+2.6+4.9=18

    6.9 1.4+1.1+3+7.5+2.6+2.4=18

    2.3 1.4+1.6+3+7.1+2.3+2.6=18

    2.6 7.4+1.1+1.6+3+2.3+2.6=18

    9.9 1.1+5+1.6+3+2.4+4.9=18

    2.4

    8.7

    4.9

    这个宏原理很简单,就是枚举出所有的可能,找出其中符合条件的列出来.参考我的另一帖回答,