以下を使用して、2 つの異なる範囲をクロス結合できます。任意のサイズの範囲を処理し、交差結合された組み合わせを指定したターゲット シートに書き込みます。
以下の例では、2 つの名前付き範囲を定義しています:newValues
とfixedValues
. これらの範囲は両方ともオン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で列のようなデカルト積を取得するにはどうすればよいですか?