# Excel VBA计算某个集合中哪6个数字的和为100（或指定数字）

A列中从A1到A20分别为数字1-20

B1为100，为计算的结果（6个数的和）

Sub CountTotal()

Application.ScreenUpdating = False

Range("c:c").ClearContents

Dim a%, b%, c%, d%

Dim e%, f%

Dim x%, tmp As String, K, totalco As Integer

Dim dic

Set dic = CreateObject("scripting.dictionary")

x = Range("a65536").End(xlUp).Row

For a = 1 To x - 5

For b = a + 1 To x - 4

For c = b + 1 To x - 3

For d = c + 1 To x - 2

For e = d + 1 To x - 1

For f = e + 1 To x

If Cells(a, 1) + Cells(b, 1) + Cells(c, 1) + Cells(d, 1) + Cells(e, 1) + Cells(f, 1) = [B1] Then

tmp = Cells(a, 1) & " + " & Cells(b, 1) & " + " & Cells(c, 1) & " + " & Cells(d, 1) & " + " & Cells(e, 1) & " + " & Cells(f, 1) & " = " & [B1]

End If

Next

Next

Next

Next

Next

Next

totalco = dic.Count

'K = dic.keys

'For x = 0 To totalco - 1

'Cells(x + 1, 3) = K(x)

'Next

[C1].Resize(dic.Count, 1) = Application.Transpose(dic.keys) '这个语句也可以用上面四句来完成

MsgBox "共有" & totalco & "条符合记录的！"

Application.ScreenUpdating = True

End Sub