2011-02-16 145 views
1

我有2列:如何在excel中獲得像列一樣的笛卡爾產品?

Col1 Col2 
    1  A 
    2  B 
    3  C 

什麼我需要得到的是隻使用Excel的這些列的所有可能組合成新列。那可能嗎?我沒有經驗使用Excel。

預期結果:

Col3 Col4 Col5 Col6 Col7 Col8 
    1 A  2 A 3 A 
    1 B  2 B 3 B 
    1 C  2 C 3 C 

在此先感謝!

回答

1

以下是關於一種可能性的一些注意事項。

strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _ 
    & ThisWorkbook.FullName _ 
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";" 

''Late binding, so no reference is needed 

Set cn = CreateObject("ADODB.Connection") 
Set rs = CreateObject("ADODB.Recordset") 
Set rs2 = CreateObject("ADODB.Recordset") 

cn.Open strCon 


strsql = "SELECT * " _ 
     & "FROM [Sheet2$a:a]" 

rs2.Open strsql, cn, 3, 3 

i = 1 
Do While Not rs2.EOF 
    strsql = "SELECT * " _ 
      & "FROM [Sheet2$a:a] a, " _ 
      & "[Sheet2$b:b] b " _ 
      & "WHERE Col1 = " & rs2!Col1 

    rs.Open strsql, cn, 3, 3 

    ''Pick a suitable empty worksheet for the results 
    Worksheets("Sheet3").Cells(2, i).CopyFromRecordset rs 

    i = i + rs.fields.Count 

    rs2.movenext 
    rs.Close 
Loop 

''Tidy up 
Set rs = Nothing 
rs2.Close 
Set rs2 = Nothing 
cn.Close 
Set cn = Nothing 
+1

也許關於爲什麼VBA解決方案要走的一點解釋可能有助於OP:問題在於,只使用Excel公式,您不能將結果放入另一個單元格。所以你必須事先知道結果集的位置和擴展才能在那裏加載一個合適的公式。相反,通過使用VBA,您可以引用任何單元並執行循環。 – 2011-02-16 17:40:26