|
回复 29楼 wenwen000424 的帖子
重新整理了一遍,两种方法都有
Private Sub CommandButton1_Click()
Dim arra()
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OleDb.4.0;Extended Properties=Excel 8.0;Data Source=" & ThisWorkbook.FullName
Set d = CreateObject("scripting.dictionary")
For Each sh In Sheets
If sh.Name <> "汇总" Then
r = sh.Range("iv1").End(xlToLeft).Column
ar = sh.Range("a1").Resize(, r)
For i = 1 To r - 1
If Not d.exists(ar(1, i)) Then
d(ar(1, i)) = s
If i = 1 Then
sql2 = ar(1, i) & ","
Else
sql2 = sql2 & " sum(iif(len(" & ar(1, i) & ")=0,0," & ar(1, i) & ")),"
End If
End If
Next
End If
Next
d(ar(1, UBound(ar, 2))) = s
sql2 = sql2 & " sum( " & ar(1, UBound(ar, 2)) & ") "
arr = d.Keys ': d.RemoveAll
z = 0
With UserForm2.ListView1
For j = 1 To .ListItems.Count
If .ListItems(j).Checked = True Then
z = z + 1
ReDim Preserve arra(1 To z)
With Sheets(.ListItems(j).Text)
ss = ""
For i = 1 To r
ss = ss & .Cells(1, i) & ","
Next
For i = 0 To UBound(arr)
If InStr(ss, arr(i)) Then
arra(z) = arra(z) & arr(i) & ","
Else
arra(z) = arra(z) & "'' as " & arr(i) & "" & ","
End If
Next
arra(z) = " select " & Left(arra(z), Len(arra(z)) - 1) & " from [" & .Name & "$] "
End With
End If
Next
End With
Sql = Join(arra, " union ") '这里是合并
If UserForm2.OptionButton2.Value = True Then Sql = "select " & sql2 & " from (" & Sql & ") group by " & ar(1, 1) & "" '这里是汇总
'MsgBox Sql
With Sheets("汇总")
.Cells.ClearContents
.Range("a1").Resize(1, UBound(arr) + 1) = d.Keys
.Range("a2").CopyFromRecordset cn.Execute(Sql)
End With
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
Private Sub UserForm_Initialize()
Call Noclose(Me.Caption)
OptionButton1.Value = True
With Me.ListView1
.ListItems.Clear
.ColumnHeaders.Clear
.View = lvwReport
.FullRowSelect = True
.Gridlines = True
.MultiSelect = True
.CheckBoxes = True
.ColumnHeaders.Add , , "工作表", 60
For i = 1 To ThisWorkbook.Sheets.Count
If Sheets(i).Name <> "汇总" Then .ListItems.Add , , Sheets(i).Name
Next i
'.SelectedItem.Selected = False '不选中
End With
End Sub
[ 本帖最后由 office2008 于 2009-1-24 13:46 编辑 ] |
|