|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
原帖由 onthetrip 于 2010-6-8 11:26 发表
我原以为可以用SQL搞定,看来不行。
谢谢你,我得好好消化一下你的代码
不要说不行啊,SQL可以的,就是麻烦一点。
5楼兄弟说的正确,EXCEL ADO 不支持full outer join,记得好像oracle 8i也是不支持full outer join的,碰到这种情况一般都是用Union + Join、Left Join之类的连接查询解决;
不过像你这样的表格格式,就算可以用full outer join,也不大可能一步到位的得到查询结果...
解决方法:
分 2 步走
1. 用Union 组织查询 得到 纵向合并的不重复的项目名称、单位
2. 用Left Join 连接查询 得到 横向合并的 且与项目名称、单位对应的数量
请测试下面的代码- Sub my_test()
- Dim iCol%, i%, j%, arr(), brr(), m%, n%
- Dim myPath$, myFiles$, Sql$, myField$
- Dim Conn As Object, rst As Object
- Application.ScreenUpdating = False
- myPath = ThisWorkbook.Path
- myFiles = Dir(myPath & "\*.xls")
- Set Conn = CreateObject("Adodb.Connection")
- Set rst = CreateObject("Adodb.Recordset")
- Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;hdr=yes;';Data Source=" & ThisWorkbook.FullName
- Sheet1.Cells.ClearContents
- Do While myFiles <> ""
- If myFiles <> ThisWorkbook.Name Then
- ReDim Preserve arr(0 To m)
- arr(m) = myFiles
- m = m + 1
- End If
- myFiles = Dir
- Loop
- For i = 0 To UBound(arr)
- Sql = "Select 项目名称,单位 from [Excel 8.0;DATABASE=" & myPath & "" & arr(i) & "].[Sheet1$]"
- ReDim Preserve brr(0 To n)
- brr(n) = Sql
- n = n + 1
- Next i
- Sql = Join(brr, " Union ")
- Sql = "Select * from (" & Sql & ") Order by 项目名称"
- Sheet1.Range("a2").CopyFromRecordset Conn.Execute(Sql)
- Set rst = Conn.Execute(Sql)
- Sheet1.Range("a1") = rst(0).Name
- Sheet1.Range("b1") = rst(1).Name
- rst.Close
- For j = 0 To UBound(arr)
- iCol = Sheet1.Range("iv1").End(xlToLeft).Column
- myField = Application.ExecuteExcel4Macro("'" & myPath & "\[" & arr(j) & "]Sheet1'!r1c3")
- Debug.Print myField
- 'Sql = "Select A." & myField & " from [Excel 8.0;DATABASE=" & myPath & "" & arr(j) & "].[Sheet1$] as A right Join [Sheet1$] as B on A.项目名称=B.项目名称 and A.单位=B.单位" 'Right Join 也可以,但不推荐。
- Sql = "Select B." & myField & " from [Sheet1$] as A Left Join [Excel 8.0;DATABASE=" & myPath & "" & arr(j) & "].[Sheet1$] as B on A.项目名称=B.项目名称 and A.单位=B.单位"
- Sheet1.Cells(1, iCol + 1) = myField
- Sheet1.Cells(2, iCol + 1).CopyFromRecordset Conn.Execute(Sql)
- Next j
- Conn.Close
- Set rst = Nothing
- Set Conn = Nothing
- Application.ScreenUpdating = True
- End Sub
复制代码 这个纯粹是为了交流学习SQL的使用方法,个人比较倾向与5楼兄弟的代码,简洁实用。
供参考 |
|