|
ADO法不需要传统意义上的打开文件,查询多工作簿速度很快,请参考:
- Sub ADO法()
- Dim cnn As Object, rs As Object, rst As Object, SQL$, Mypath$, MyFile$, s$, t$, a, arr, i&
- Application.ScreenUpdating = False
- arr = Range("A2:J3")
- For i = 1 To UBound(arr, 2)
- If arr(2, i) <> "" Then
- If i = 1 Then
- t = t & " and " & arr(1, i) & "=#" & arr(2, i) & "#"
- Else
- t = t & " and " & arr(1, i) & "='" & arr(2, i) & "'"
- End If
- End If
- Next
- If t = "" Then Exit Sub
- t = Mid(t, 5)
- Range("A6:L65536").ClearContents
- Mypath = ThisWorkbook.Path & ""
- MyFile = Dir(Mypath & "*.xls")
- Do While MyFile <> ""
- If MyFile <> ThisWorkbook.Name Then
- Set cnn = CreateObject("adodb.connection")
- cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=excel 8.0;Data Source=" & Mypath & MyFile
- Set rs = cnn.OpenSchema(20)
- Do Until rs.EOF
- If rs.Fields("TABLE_TYPE") = "TABLE" Then
- s = Replace(rs("TABLE_NAME").Value, "'", "")
- If Right(s, 1) = "$" Then
- Set rst = cnn.Execute("[" & s & "a3:a3]")
- If rst.Fields(0).Name = "生产日期" Then
- SQL = "select 生产日期,处理结果,产品名称,产品编码,防伪码,入库,生产部门,生产车间,质检员,备注,'" & Replace(MyFile, ".xls", "") & "','" & Replace(s, "$", "") & "' from [" & s & "a3:j] where" & t
- Set rst = cnn.Execute(SQL)
- If Not rst.EOF Then Range("a65536").End(xlUp).Offset(1).CopyFromRecordset rst
- End If
- End If
- End If
- rs.MoveNext
- Loop
- End If
- MyFile = Dir()
- Loop
- rs.Close
- Set rs = Nothing
- rst.Close
- Set rst = Nothing
- cnn.Close
- Set cnn = Nothing
- End Sub
复制代码 |
|