Excel VBA条件三数组合计数:统计首数为1的组合数量方案
首数为1的三数组合统计实现方案
需求说明
无需输出每个首数为1的三数组合,仅在程序运行结束后统计并输出该类组合的总数,格式示例:i = 10
高效实现代码(数学公式法)
利用组合数学公式直接计算,比循环遍历效率更高,适合数据量较大的场景:
Sub Count_Combo_StartWith_1() Dim lastRow As Long Dim comboCount As Long ' 关闭屏幕刷新和自动计算,提升运行速度 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual ' 获取A列最后一行的行号 lastRow = Cells(Rows.Count, "A").End(xlUp).Row ' 首数固定为第1行数字时,剩余两个数从第2行到最后一行中选2个 ' 组合数公式:C(n,2) = n*(n-1)/2,n是除首数外的数字总数 If lastRow >= 3 Then comboCount = (lastRow - 1) * (lastRow - 2) / 2 Else comboCount = 0 ' 数字不足3个,无法形成三数组合 End If ' 将结果输出到B1单元格,也可改用MsgBox弹窗显示 Cells(1, "B").Value = "i = " & comboCount ' 恢复默认设置 Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub
循环逻辑版本(兼容原代码思路)
如果偏好通过循环遍历统计,可使用以下代码,去掉原代码中的无效逻辑:
Sub Count_Combo_StartWith_1_Loop() Dim lastRow As Long Dim comboCount As Long Dim j As Long, k As Long Application.ScreenUpdating = False Application.Calculation = xlCalculationManual lastRow = Cells(Rows.Count, "A").End(xlUp).Row comboCount = 0 ' 初始化计数器 ' 仅遍历首数为第1行的情况,无需循环所有i值 If 1 <= lastRow - 2 Then For j = 2 To lastRow - 1 For k = j + 1 To lastRow comboCount = comboCount + 1 ' 每找到一个符合条件的组合就计数+1 Next k Next j End If Cells(1, "B").Value = "i = " & comboCount Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub
原代码问题修正说明
原Three_Combo1代码存在两处冗余/错误:
- 变量
l未初始化,首次赋值单元格时会触发错误; Else分支中的l = l + 1完全无效,既不输出内容也不影响统计,纯粹浪费性能。
内容的提问来源于stack exchange,提问作者Swany_08
相关产品推荐
相关产品推荐

