Excel VBA宏以生成可能组合的列表

时间:2013-07-16 15:43:40

标签: excel-vba combinations vba excel

我正在尝试编写一个excel宏来生成可能的组合列表。

我在不同的列中有一系列固定的值

A,B,C,D - 每个都在它自己的专栏中。

我有一个要用A,B,C或D替换的新值列表,并希望生成所有组合。

新值列表,即1,2,3,4

我会得到总共16种不同的组合

例如,

1BCD
2BCD
3BCD
4BCD
A1CD
A2CD
A3CD

...
ABC1
ABC2
ABC3
ABC4

我不确定这是否清楚,但我想通过迭代每一列来生成组合,以生成插入新值的可能组合。

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容交叉连接两个不同的范围。它将处理任何大小的范围,并将交叉连接组合写入您指定的目标工作表。

在下面的示例中,我定义了两个命名范围:newValuesfixedValues。这两个范围都在Sheet1上。然后我遍历范围并将所有组合写入Sheet2

Sub CrossJoinMyRanges()
    Dim ws As Worksheet
    Dim newValues As Range
    Dim cell As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")
    Set newValues = ws.Range("newValues")

    ' loop through the new values
    For Each cell In newValues
        Call ReplaceMe(cell.Value, ws)
    Next cell
End Sub

Sub ReplaceMe(replacement As String, ws As Worksheet)
    Dim fixedValues As Range
    Dim cell As Range

    Set fixedValues = ws.Range("fixedValues")

    ' outer loop through fixedValues
    For Each cell In fixedValues
        Call PrintReplacedValues(cell.Row, replacement)
    Next cell
End Sub

Sub PrintReplacedValues(rowNumber As Long, replacement As String)
    Dim wb As Workbook
    Dim src As Worksheet
    Dim tgt As Worksheet
    Dim fixedValues As Range
    Dim cell As Range
    Dim printMe As String
    Dim x As Long, y As Long

    Set wb = ThisWorkbook
    Set src = wb.Sheets("Sheet1")
    Set tgt = wb.Sheets("Sheet2")
    Set fixedValues = src.Range("fixedValues")
    y = 1
    x = tgt.Range("A" & tgt.Rows.Count).End(xlUp).Row + 1

    ' inner loop through fixed values
    For Each cell In fixedValues
        ' replace the fixed value with the replacement
        ' if the loops intersect
        If cell.Row = rowNumber Then
            printMe = replacement
        Else
        ' otherwise keep the fixed value
            printMe = cell
        End If
        ' write to the target sheet
        tgt.Cells(x, y).Value = printMe
        y = y + 1
    Next cell
End Sub

如果我的方法不符合您的要求,您可以查看替代解决方案中的一些类似问题:

Excel vba to create every possible combination of a Range

How can i obtain cartesian product like columns in excel?