返回首页
当前位置: 主页 > Excel教程 > Excel VBA教程 >

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

时间:2012-06-17 02:09来源:Office教程学习网 www.office68.com编辑:麦田守望者

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

B1为100,为计算的结果(6个数的和)

现在计算A列中哪6个数字的和为100

符合条件的就放在C列中

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]
dic.Add tmp, ""
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

自己感觉这样的算法速度似乎比较慢

慢慢再琢磨有没有快点的算法

如果A列中的数字越多,算起来就越慢了。

类似的过程别人早就有了,只是人家用别的算法(自己写的看得明白,别人写的看起来好费劲

------分隔线----------------------------
标签(Tag):excel excel2007 excel2010 excel2003 excel技巧 excel教程 excel实例教程 excel2010技巧
------分隔线----------------------------
推荐内容
猜你感兴趣