【问题标题】:vba code to get all combinations if they equal a cell如果它们等于一个单元格,则获取所有组合的 vba 代码
【发布时间】:2019-02-09 11:56:30
【问题描述】:

所以我有一个 15 列 x 100 行的数据表,其中包含所有不同的百分比,从 100%-0%,我希望从中获得所有可能的组合。现在我有一个可以将组合放入另外 15 列的代码。问题是,如何使代码仅输出加在一起 ​​= 100% 的组合。这是我现在拥有的代码。

Sub Perm()
  Dim rSets As Range, rOut As Range
  Dim vArr As Variant, lRow As Long

  Set rSets = Range("A1").CurrentRegion
  ReDim vArr(1 To rSets.Columns.Count)
  Set rOut = Cells(1, rSets.Columns.Count + 2)
  Perm1 rSets, vArr, rOut, 1, lRow
  End Sub

  Sub Perm1(rSets As Range, ByVal vArr As Variant, rOut As Range, ByVal lSetN As Long, lRow As Long)
  Dim j As Long

  For j = 1 To rSets.Rows.Count
      If rSets(j, lSetN) = "" Then Exit Sub
      vArr(lSetN) = rSets(j, lSetN)
      If lSetN = rSets.Columns.Count Then
          lRow = lRow + 1
          rOut(lRow).Resize(1, rSets.Columns.Count).Value = vArr
      Else
          Perm1 rSets, vArr, rOut, lSetN + 1, lRow
      End If
  Next j
  End Sub

【问题讨论】:

    标签: vba excel combinations permutation


    【解决方案1】:

    我假设您的百分比是十进制值而不是文本(0.3 而不是 30%)。刚刚添加了一个 if 语句,求和的 vArr 并检查总和是否为 1。

      Sub Perm1(rSets As Range, ByVal vArr As Variant, rOut As Range, ByVal lSetN As Long, lRow As Long)
      Dim j As Long
    
      For j = 1 To rSets.Rows.Count
          If rSets(j, lSetN) = "" Then Exit Sub
          vArr(lSetN) = rSets(j, lSetN)
          If lSetN = rSets.Columns.Count Then
              If WorksheetFunction.Sum(vArr) = 1 Then
                  lRow = lRow + 1
                  rOut(lRow).Resize(1, rSets.Columns.Count).Value = vArr
              End If
          Else
              Perm1 rSets, vArr, rOut, lSetN + 1, lRow
          End If
      Next j
    

    【讨论】:

    • 感谢您的帮助。是的,百分比是十进制值。有什么办法可以加快速度,因为它已经运行了一个小时并且还没有完成,所以我不确定这是否有效?
    • 我已经检查了较小的数据集,它似乎确实有效......但是在重新阅读您的问题并查看您正在使用的数据量之后,您可能需要重新考虑范围。我不是数学家,但使用此算法,您正在评估 100^15 种组合(1 000 000 000 000 000 000 000 000 000 000)。
    • 您认为运行完成它需要多长时间?你认为我还能用什么其他方式做到这一点?
    • 再说一遍,我不是数学家,但即使每秒 100 000 次组合,每年 31 536 000 秒,运行时间也将约为 317 097 919 837 645 865 年。我的计算机每秒大约有 20 000 种组合,而数据集则小得多,只有 16 行 5 列(1 048 576 种组合)。您拥有的代码无疑是蛮力方法。不确定您分析的数据是什么,但您可能需要查看它,看看是否有其他模式可以找到......或者重新调整您的范围......或者投资一台量子计算机(最后我听说它们只是15 密尔)。
    • 他们可能有一台备用量子计算机供您当地的租赁中心使用
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 2020-02-17
    • 2020-07-10
    • 2013-03-29
    相关资源
    最近更新 更多