1

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

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

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

例如列:

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

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

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

它像这样吐出:

D0032333RCVFX

D0032333RCVDF

D0032333RCHSF

D0034833RCVFX

D0034833RCVDF

等等等等.....

4

1 回答 1

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 开始表示“仅顶行”)调用此函数。它假定任何空白都位于每列的底部。否则,它将返回一个字符串,该字符串是每列中值组合的串联,正如您所描述的那样。

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

在此处输入图像描述

于 2013-08-17T03:58:45.417 回答