Sub ADOstudy() Dim szSQL As String Set szConnect = CreateObject("ADODB.connection") SourceFile = ThisWorkbook.FullName SourceSheet = "RAW" szConnect.Open = "provider=microsoft.jet.oledb.4.0;extended properties='Excel 8.0;HDR=No';data source=" & SourceFile szSQL = "SELECT qty FROM (SELECT f1 AS name1 FROM [表2$] ) AS A " & _ "LEFT JOIN " & _ "(SELECT f1 AS name2,f2 AS qty FROM [" & SourceSheet & "$] ) AS B ON A.name1=B.name2" ThisWorkbook.Sheets("表2").[B1].CopyFromRecordset szConnect.Execute(szSQL) szConnect.Close: Set szConnect = Nothing End Sub 因为要在另一表中查询与“表2”第1列相对应的另一列值,所以表2第1列为基准列, 我们可以先用语句 SELECT f1 AS name1 FROM [表2$]
将它取出; 而语句 SELECT f1 AS name2, f2 AS qty FROM [" & SourceSheet & "$] 可以取出SourceSheet表中的两列,要想让第2列(即qty) 在基准列(表2第1列)的旁边(表2第2列)放置的时候能与基准列的项目一一对应,就可以使用 LEFT JOIN 语句; SELECT qty FROM (SELECT f1 AS name1 FROM [表2$] ) AS A " & _ "LEFT JOIN " & _ "(SELECT f1 AS name2,f2 AS qty FROM [" & SourceSheet & "$] ) AS B ON A.name1=B.name2 它的效果就是以 LEFT JOIN 语句左边的查询序列为基准,显示第一个 SELECT 后所指定的字段值,这个字段值可以是其后任意一个查询语句结果中的字段值,本例中即为“qty”。这个qty的排列就会以表2第1列为基准,与第1列是一一对应的了。
Lj89coWB.rar
(13.59 KB, 下载次数: 33)
[此贴子已经被作者于2007-1-6 8:48:34编辑过] |