【问题标题】:Combination Generator yet keep in order组合发电机还保持秩序
【发布时间】:2013-08-16 23:08:32
【问题描述】:

想知道是否有人可以帮助我。我难住了。好久没用excel了……

我有 9 列,每个单元格中的值不同,每列的单元格数量不同。

我需要一个公式/宏来输出单元格的所有组合,但仍保持与列的完全相同的顺序。

例如 列:

D   / 003 / 23  / 3 / 3R  / C  / VFX

... / 005 / 48  / 3 / 12  / .. / VDF

... / 007 / ... / 1 / ... /... / HSF

它会像这样吐出:

D0032333RCVFX

D0032333RCVDF

D0032333RCHSF

D0034833RCVFX

D0034833RCVDF

等等.... 等等……

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    大概你会想用“序列号”来调用这个函数——这样你就可以调用“第 N 个组合”。然后问题分为两部分:

    第 1 部分:对于给定的“序列号”,找出您需要每列的哪个元素。如果每列中有相同数量的元素 E,那就很简单了:就像在基数 E 中写 N。当每列中的元素数量不同时,这有点棘手 - 像这样:

    Option Base 1
    Option Explicit
    
    Function combinationNo(r As Range, serialNumber As Integer)
    ' find the number of entries in each column in range r
    ' and pick the Nth combination - where serialNumber = 0 
    ' gives the top row
    ' assumes not all columns are same length
    ' but are filled starting with the first row
    
    Dim ePerRow()
    Dim columnIndex As Integer
    Dim totalElements As Integer
    Dim i, col
    Dim tempString As String
    
    ReDim ePerRow(r.Columns.Count)
    totalElements = 1
    i = 0
    For Each col In r.Columns
      i = i + 1
      ePerRow(i) = Application.WorksheetFunction.CountA(col)
     totalElements = totalElements * ePerRow(i)
    Next
    
    If serialNumber >= totalElements Then
      combinationNo = "Serial number too large"
      Exit Function
    End If
    
    tempString = ""
    For i = 1 To UBound(ePerRow)
      totalElements = totalElements / ePerRow(i)
      columnIndex = Int(serialNumber / totalElements)
      tempString = tempString & r.Cells(columnIndex + 1, i).Value
      serialNumber = serialNumber - columnIndex * totalElements
    Next i
    
    combinationNo = tempString
    
    End Function
    

    您使用列所在的范围和序列号(从 0 开始表示“仅顶行”)调用此函数。它假定任何空白都位于每列的底部。否则,它将返回一个字符串,该字符串是每列中值组合的串联,正如您所描述的那样。

    编辑也许下面的图片会有所帮助,它显示了它的使用方式和实际作用。请注意,第一个引用(对不同长度的列的表)是 absolute 引用(使用$ 符号,因此当您将它从一个单元格复制到另一个单元格时,它一直引用范围相同),而第二个参数是 relative (因此它依次指向0, 1, 2, 3 等)。

    【讨论】:

    • 好吧,我迷路了……我以前从未使用过 VBA。
    • 我了解大部分问题,但这部分:
    • 在范围 r' 中找到每列中的条目数并选择第 N 个组合 - 其中 serialNumber = 0 ' 给出顶行 ' 假设并非所有列的长度都相同 ' 但以第一排把我弄丢了……
    • 我添加的图片有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 2013-07-22
    • 2017-12-23
    • 1970-01-01
    • 2018-04-17
    • 2022-06-13
    • 1970-01-01
    • 2017-05-29
    相关资源
    最近更新 更多