2

可能な組み合わせのリストを生成する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

これが明確かどうかはわかりませんが、各列を繰り返して組み合わせを生成し、新しい値が挿入された可能な組み合わせを生成したいと思います。

4

1 に答える 1

1

以下を使用して、2 つの異なる範囲をクロス結合できます。任意のサイズの範囲を処理し、交差結合された組み合わせを指定したターゲット シートに書き込みます。

以下の例では、2 つの名前付き範囲を定義しています: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

Excelで列のようなデカルト積を取得するにはどうすればよいですか?

于 2013-07-16T18:20:57.117 に答える