|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 xmyjk 于 2011-11-21 22:08 编辑
分析题目已知条件:(1)工作表数量已知:80个;
(2)格式已知:每个工作簿都有3个格式相同的工作表,名称分别是1部门、2部门和3部门
经上分析,不需在用ADO植入连接或者打开表获取表名,直接用ADO查询获取数据且不打开表可加快效率,不过没记错的话,ADO+SQL中,UNION ALL最多支持连接49个表。那就没16个工作薄做一次ADO连接吧。
程序如下:- Option Explicit
- Sub 按钮2_Click()
- Dim d, j&, cn, T As Double, sql$, MyPath$, MyFiles$, TWb$, bm$, m&, nm&
- Application.ScreenUpdating = False
- T = Timer
- Range([A4], [H65536].End(3).Offset(1)).Clear
- Set d = CreateObject("scripting.dictionary")
- Set cn = CreateObject("ADODB.Connection")
- TWb = ThisWorkbook.Name
- MyPath = ThisWorkbook.Path
- MyFiles = Dir(MyPath & "\*.xls")
- Do While MyFiles <> ""
- If TWb <> MyFiles Then
- m = m + 1
- bm = Replace(MyFiles, ".xls", "")
- For j = 1 To 3
- sql = "Select """ & bm & """ ,""" & j & "部门"" ,* From [excel 8.0;HDR=NO;DATABASE=" & MyPath & "" & MyFiles & "].[" & j & "部门$]"
- d(sql) = ""
- Next
- If m Mod 16 = 0 Then
- sql = Join(d.Keys, " UNION ALL ")
- sql = "SELECT F1,F2,F3,F4,F5,F6,EXPR1000,EXPR1001 from (" & sql & ") WHERE F2 = '" & Cells(2, 3).Value & "'"
- sql = Replace(sql, "[excel 8.0;HDR=NO;DATABASE=" & MyPath & "" & MyFiles & "].", "")
- cn.Open "provider=microsoft.jet.oledb.4.0;extended properties='excel 8.0;hdr=no';data source=" & MyPath & "" & MyFiles
- [a65536].End(3).Offset(1).CopyFromRecordset cn.Execute(sql)
- cn.Close
- d.RemoveAll
- nm = nm + 1
- End If
- End If
- MyFiles = Dir
- Loop
- Set cn = Nothing: Set d = Nothing
- Application.ScreenUpdating = True
- MsgBox "取数" & nm & "次;耗时" & Timer - T & "秒"
- End Sub
复制代码 |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?免费注册
x
评分
-
1
查看全部评分
-
|