|
本题目还可以使用ADO法,有多表联合查询、ADO加数组加字典,下面是后者,速度有所提高:- Sub ADO加数组加字典()
- '引用Microsoft Scripting Runtime
- tt = Timer
- Dim cnn As New ADODB.Connection
- Dim rs As ADODB.Recordset
- Dim rst As ADODB.Recordset
- Dim SQL$, arr_Field
- Dim p$, f$, arr, brr(1 To 60000, 1 To 256), ds As Object
- Dim i&, j, m&, n&, r, y$, sh As Worksheet
- Set d = CreateObject("scripting.dictionary")
- Set ds = CreateObject("scripting.dictionary")
- ds("单位") = 1
- ds("年") = 2
- n = 2
- p = ThisWorkbook.Path & ""
- f = Dir(p & "*.xls")
- Application.ScreenUpdating = False
- Do While f <> ""
- If f <> ThisWorkbook.Name Then
- Set cnn = New ADODB.Connection
- cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & p & f
- Set rs = cnn.OpenSchema(adSchemaTables)
- Do Until rs.EOF
- If rs.Fields("TABLE_TYPE") = "TABLE" Then
- shn = rs("TABLE_NAME").Value
- If Right(shn, 1) = "$" Then
- Set rst = cnn.Execute("[" & shn & "]")
- If rst.Fields(0).Name = "单位" Then
- y = Left$(f, 4)
- Set rst = New ADODB.Recordset
- SQL = "select * from [" & shn & "] where not 单位 is null"
- rst.Open SQL, cnn, 1, 3
- With rst
- ReDim arr_Field(1 To .Fields.Count - 1)
- For j = 1 To .Fields.Count - 1
- arr_Field(j) = .Fields(j).Name
- If Not ds.Exists(arr_Field(j)) Then
- n = n + 1
- ds(arr_Field(j)) = n
- End If
- Next
- For i = 1 To .RecordCount
- m = m + 1
- brr(m, 1) = .Fields(0).Value
- brr(m, 2) = y
- For j = 1 To .Fields.Count - 1
- brr(m, ds(arr_Field(j))) = .Fields(j).Value
- Next
- .MoveNext
- Next
- End With
- End If
- End If
- End If
- rs.MoveNext
- Loop
- End If
- f = Dir
- Loop
- Cells.ClearContents
- [a1].Resize(, n) = ds.keys
- [a2].Resize(m, n) = brr
- rs.Close
- Set rs = Nothing
- rst.Close
- Set rst = Nothing
- cnn.Close
- Set cnn = Nothing
- Application.ScreenUpdating = True
- MsgBox Timer - tt
- End Sub
复制代码 |
|