|
dengxiyin 发表于 2013-11-14 22:56
您好,版主,能否发一个excel附件及这个宏注释我。谢谢! - Dim arrf(), mf& '模块级变量,主程序和子程序都可以使用
- Sub Macro1()
- Dim Mypath$, Fso As Object, i&, m&, brr(1 To 60000, 1 To 3)
- Dim cnn As Object, rs As Object, rst As Object
- With Application.FileDialog(msoFileDialogFolderPicker) '指定文件夹
- If .Show = False Then Exit Sub
- Mypath = .SelectedItems(1)
- End With
- Application.ScreenUpdating = False '关闭屏幕刷新
- Set Fso = CreateObject("Scripting.FileSystemObject") '创建Fso对象
- sFileType = "*.xls" '文件类型
- Call GetFiles(Mypath, sFileType, Fso) '调用查询所有子文件夹中的所有文件子程序
- For i = 1 To mf '逐个xls文件
- Set cnn = CreateObject("ADODB.Connection") '创建连接对象
- cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;hdr=no';Data Source=" & arrf(i) '连接该文件
- Set rst = cnn.OpenSchema(20) 'adSchemaTables'查找工作表
- Do Until rst.EOF '有工作表
- If rst.Fields("TABLE_TYPE") = "TABLE" Then '判断是工作表
- s = Replace(rst("TABLE_NAME").Value, "'", "") '去掉多余的单引号
- If Right(s, 1) = "$" Then '去掉像打印区域等假工作表
- Set rs = cnn.Execute("[" & s & "a1:a1]") '先查A1单元格
- If rs.Fields(0).Value <> "" Then '如果有值
- m = m + 1 '加一行
- brr(m, 1) = m '序号
- brr(m, 2) = rs.Fields(0).Value 'A1值
- brr(m, 3) = cnn.Execute("[" & s & "a3:a3]").Fields(0).Value 'A3值
- End If
- End If
- End If
- rst.MoveNext '下一个工作表
- Loop
- Next
- Range("A5:F65536").ClearContents '清除原数据
- [a5].Resize(m, 3) = brr '写数据
- rs.Close '下面是关闭连接,释放内存
- rst.Close
- cnn.Close
- Set rs = Nothing
- Set rst = Nothing
- Set cnn = Nothing
- mf = 0
- Erase arrf
- Set Fso = Nothing
- Application.ScreenUpdating = True
- End Sub
复制代码 Private Sub GetFiles(ByVal sPath$, ByVal sFileType$, Fso As Object) '查询所有子文件夹中的所有文件子程序,原理不用管它 |
评分
-
1
查看全部评分
-
|