Excel / VBA / MS Query来创buildRange的每个可能的组合

我有一个问题,我一直没有find解决办法。

我有一个电子表格5 – > 10? 数据列。 所有这些都是不同的,但有些列是相互关联的(如果A3 = 1,那么B3 = A和C3 = a)。 每列包含3 – > 6参数的变化,我需要创build它们的所有可能的组合。

列中的初始数据:

在这里输入图像说明

预期结果:

预期结果

开尔文以前几乎有类似的问题 ,但是这并不适用于我..

你可以通过交叉连接来使用SQL。 下面是我做的和testing的一个小例子。 你将不得不适应你的需求。 在我的示例中,test1和test3是sheet1的第一行中的列名称。

 Sub SQLCombineExample() Dim con Dim rs Set con = CreateObject("ADODB.Connection") con.Open "Driver={Microsoft Excel Driver (*.xls)};" & _ "DriverId=790;" & _ "Dbq=" & ThisWorkbook.FullName & ";" & _ "DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;" Set rs = CreateObject("ADODB.Recordset") Set rs = con.Execute("select distinct a.[test1], b.[test3] from [Sheet1$] as a , [Sheet1$] as b ") Range("f1").CopyFromRecordset rs Set rs = Nothing Set con = Nothing End Sub 

结果

从我在你的照片中看到的,唯一可以改变组合的项目就是第4栏中的那个:(1; A; a; item4;#¤),(2; B; b; item4;&#)和3; C; c; item4;¤%&)

如果这确实是你正在尝试做下面的代码应该工作:

 Sub Combination() Dim i As Integer, j As Integer, k As Integer For k = 0 To 2 'loop through (1 A a #¤), (2 B b &#¤) and (3 C c ¤%&) j = 3 'column 4 items For i = 0 To 6 Step (3) 'loop 3 by 3 (output starts in row 10) Cells(10 + k + i, 1) = Cells(3 + k, 1) Cells(10 + k + i, 2) = Cells(3 + k, 2) Cells(10 + k + i, 3) = Cells(3 + k, 3) Cells(10 + k + i, 5) = Cells(3 + k, 5) Cells(10 + k + i, 4) = Cells(j, 4) j = j + 1 Next i Next k End Sub 
 Sub CopyAllCombinationsToRange() Dim arSource Dim arResult Dim i As Long, j As Long, combinationCount As Long, counter As Long arSource = Range(Cells(2, 1), Cells(Rows.Count, 5).End(xlUp)).Value combinationCount = UBound(arSource, 2) * UBound(arSource, 2) ReDim arResult(4, combinationCount - 1) For i = 1 To UBound(arSource, 1) For j = 1 To UBound(arSource, 1) arResult(0, counter) = arSource(i, 1) arResult(1, counter) = arSource(i, 2) arResult(2, counter) = arSource(i, 3) arResult(3, counter) = arSource(i, 4) arResult(4, counter) = arSource(j, 5) counter = counter + 1 Next Next Sheet2.Range("A1").Resize(UBound(arResult, 2), 5) = WorksheetFunction.Transpose(arResult) End Sub 

在这里输入图像说明