Excel函数或VBA脚本来组合范围

我有两列各有不同数量的行。 在这种情况下,我想合并(标量多个?多个matrix?)A1中的项目与范围(B1:B50),然后重复列A中的每个项目。

理想情况下,两个值将用逗号分隔。 这是我想要完成的 。

什么是最好的路线去? matrix函数可以用于组合文本吗?

试试这个代码:

Sub sample() Dim lastRowA As Long, lastRowB As Long, row As Long lastRowA = Range("A" & Rows.Count).End(xlUp).row lastRowB = Range("B" & Rows.Count).End(xlUp).row row = 1 For i = 1 To lastRowA For j = 1 To lastRowB Cells(row, 4) = Cells(i, 1) Cells(row, 5) = Cells(i, 1) & "," & Cells(j, 2) row = row + 1 Next Next End Sub 

如果您从SQL获取数据,则CROSS JOIN将为您提供两组数据的笛卡尔乘积。

那么你可以连接在一起。

这里使用SQL-Server就是一个例子:

 CREATE TABLE #x (columnX CHAR(1)); INSERT INTO #x values ('a'), ('b'), ('c'); CREATE TABLE #y (columnY CHAR(1)); INSERT INTO #y values ('d'), ('e'), ('f'); SELECT #x.columnX, #y.columnY, #x.columnX + ', ' + #y.columnY FROM #x CROSS JOIN #y