《Excel你問我答挑戰(zhàn)》兩列數(shù)據(jù)列出全部組合



Sub aa()
'創(chuàng)建 SQL 使用對(duì)象
Dim Cnn As Object, Rs As Object
Set Cnn = CreateObject("ADODB.Connection")
Set Rs = CreateObject("ADODB.Recordset")
Cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & ThisWorkbook.FullName
'以上格式是固定的,不需要記
strSQL = "select?a.名稱,b.名稱 from [sheet1$B:B] as a left join [sheet1$C:C] as b on a.名稱 <> b.名稱 "
'SQL 語句,根據(jù)需要變化,以字符串形式保存
'重點(diǎn)說下 [sheet1$B:B] 指的是 Sheet1 表中 B整列,[Sheet1$] 是整個(gè)表 ,[sheet1$C:C] as b 中的as 起別名 b
'執(zhí)行SQL 語句
Rs.Open strSQL, Cnn
將結(jié)果寫入表中
Range("E2").CopyFromRecordset Rs
'關(guān)閉SQL對(duì)象
Rs.Close
Cnn.Close
Set Rs = Nothing
Set Cnn = Nothing
標(biāo)簽: