|
原帖由 onthetrip 于 2010-7-21 15:54 发表
为什么我将union 改成union all 就不能执行了呢?
----------------------
另外:如果分表有重复的项目,是不是得加一个SQL先将分表的源数据进行先期处理,处理成无重复的项目后,才能再执行后面的union和left join两个 ...
可以使用Union all 啊,
Sql = Join(brr, " Union all ") '这里改Union all,注意:Union all前后都有空格。不过为什么要用Union all?
再回答另外:
分表会有什么重复的项目,总共就3个字段:项目名称,单位,数量?记得你的附件中标注过项目名称,单位不重复。
难道是分表里要 "Select 项目名称,单位 ,sum(数量)as 数量 from 分表 group by 项目名称,单位" 这样?如果是这样的话,稍微改写一下Sql=“” 的语句就行了,不需要再Sql先期处理了,参见本楼代码。
Union本身就是去重复的纵向连接,Union all 是不管重复不重复,全部连在一起... 可以参考Sql手册:http://www.w3school.com.cn/sql/sql_union.asp- 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")
- Sql = "Select B." & myField & " from [Sheet1$] as A Left Join (Select 项目名称,单位,Sum(" & myField & ") as " & myField & " from [Excel 8.0;DATABASE=" & myPath & "" & arr(j) & "].[Sheet1$] Group by 项目名称,单位) 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
复制代码 供参考 |
|