大概你会想用“序列号”来调用这个函数——这样你就可以调用“第 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 开始表示“仅顶行”)调用此函数。它假定任何空白都位于每列的底部。否则,它将返回一个字符串,该字符串是每列中值组合的串联,正如您所描述的那样。
编辑也许下面的图片,它显示了它是如何使用的以及它实际做了什么,会有所帮助。请注意,第一个引用(对不同长度的列的表)是绝对引用(使用$
符号,因此当您将其从一个单元格复制到另一个单元格时,它一直引用相同的范围),而第二个参数是相对的(所以它0, 1, 2, 3
依次指向等)。