您可以使用以下内容交叉连接两个不同的范围。它将处理任何大小的范围并将交叉连接的组合写入您指定的目标工作表。
在下面的示例中,我定义了两个命名范围: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 中获得笛卡尔积,如列?