|
楼主 |
发表于 2012-7-30 11:23
|
显示全部楼层
本帖最后由 fankairong 于 2012-7-30 11:33 编辑
到这里就已经完全结束了。现附上完整的附件,里面的关键就是strSQL,各位学习的时候建议挨个测试SQL看其效果。测试办法是将后面的strSQL前面做个标注,使其不运行
- Sub Transform()
- sAddress1 = Sheets("源数据").Range("a1").CurrentRegion.Address(0, 0) '将地址用相对引用方法表示,如果用绝对引用的话,会出现多个$从而导至错误
- sAddress2 = Sheets("源数据").Range("f1").CurrentRegion.Address(0, 0)
- Dim cnn As New ADODB.Connection
- Dim rs As New ADODB.Recordset
- cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & ThisWorkbook.FullName
- strsql = "select * from [源数据$" & sAddress1 & "] union all select * from [源数据$" & sAddress2 & "]" '第一步合并源数据
- strsql = "select 姓名,月份,sum([金额]) as 合计 from (select * from [源数据$" & sAddress1 & "] union all select * from [源数据$" & sAddress2 & "]) group by 姓名,月份" '第二步分组
- strsql = "Transform SUM(金额) select 月份 as 合计 from (select * from [源数据$" & sAddress1 & "] union all select * from [源数据$" & sAddress2 & "]) GROUP BY 姓名,月份 pivot 姓名" '行标题为{},列标题为{}分组
- strsql = "Transform SUM(金额) select 姓名 as 合计 from (select * from [源数据$" & sAddress1 & "] union all select * from [源数据$" & sAddress2 & "]) GROUP BY 月份,姓名 pivot 月份" '行标题为{姓名},列标题为{月}分组
- strsql = "Transform SUM(金额) select 月份 as 合计 from (select * from [源数据$" & sAddress1 & "] union all select * from [源数据$" & sAddress2 & "]) GROUP BY 月份 pivot 姓名" '行标题为{月},列标题为{姓名}分组,去除行标题重复
- strsql = "Transform SUM(金额) select 姓名 as 合计 from (select * from [源数据$" & sAddress1 & "] union all select * from [源数据$" & sAddress2 & "]) GROUP BY 姓名 pivot 月份" '行标题为{姓名},列标题为{月}分组,去除行标题重复
- rs.Open (strsql), cnn
- [a20].CopyFromRecordset cnn.Execute(strsql)
- For Each Field In rs.Fields
- aa = Field.Name
- [a19].Offset(0, i) = Field.Name
- i = i + 1
- Next
- Set rs = Nothing
- Set cnn = Nothing
- End Sub
复制代码
数据透视Transform.rar
(11.02 KB, 下载次数: 650)
|
评分
-
4
查看全部评分
-
|