|
楼主 |
发表于 2019-7-1 15:28
|
显示全部楼层
- Sub 提取总分()
- Dim Fso As Object, oFolder As Object, oFile As Object, cnn As Object, rs As Object, m&, arr$()
- Dim sFilePath As String, Sql1 As String, Sql2 As String, Sql3 As String
- Set Fso = CreateObject("Scripting.FileSystemObject")
- sFilePath = ThisWorkbook.Path & "\Files"
- Set oFolder = Fso.GetFolder(sFilePath) '获取Files所在文件夹
- ReDim arr$(1 To oFolder.Files.Count, 1 To 4) '初始化arr数组
- Application.ScreenUpdating = False '禁止数据更新,避免因数据更新时引起闪屏,提高运行速度
- Worksheets("数据缓存表").UsedRange.ClearContents '情况sheet2内容
-
- For Each oFile In oFolder.Files
- If oFile.Name Like "*经理*.xls*" Then
- Sql1 = "SELECT * FROM [月度-工程经理(土建)$b3:b3]" '项目名称
- Sql2 = "SELECT * FROM [月度-工程经理(土建)$e3:e3]" '姓名
- Sql3 = "SELECT * FROM [月度-工程经理(土建)$k1:k1]" '分数
- Call oSql(cnn, rs, oFile, Sql1, Sql2, Sql3, arr(), m)
- ElseIf oFile.Name Like "*总监*.xls*" Then
- Sql1 = "SELECT * FROM [月度-工程总监$b3:b3]" '项目名称
- Sql2 = "SELECT * FROM [月度-工程总监$e3:e3]" '姓名
- Sql3 = "SELECT * FROM [月度-工程总监$k1:k1]" '分数
- Call oSql(cnn, rs, oFile, Sql1, Sql2, Sql3, arr(), m)
- ElseIf oFile.Name Like "*平台*.xls*" Then
- Sql1 = "SELECT '平台' FROM [平台$]" '姓名
- Sql2 = "SELECT * FROM [平台$c3:c3]" '姓名
- Sql3 = "SELECT * FROM [平台$b1:b1]" '分数
- Call oSql(cnn, rs, oFile, Sql1, Sql2, Sql3, arr(), m)
- End If
- Next
-
- If m > 0 Then Sheets("数据缓存表").[a1].Resize(m, 4) = arr
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- Set oFile = Nothing
- Set oFolder = Nothing
- Set Fso = Nothing
- Worksheets("数据缓存表").Range("c:c") = Worksheets("数据缓存表").Range("c:c").Value '数据缓存表C列转换为数字格式
- Application.ScreenUpdating = True
- End Sub
- Sub oSql(cnn, rs, ByVal oFile As Object, Sql1, Sql2, Sql3, arr$(), m&)
- m = m + 1
- Set cnn = CreateObject("ADODB.Connection")
- cnn.Open "Provider=Microsoft.ace.OLEDB.12.0;Extended Properties='Excel 12.0;hdr=no';Data Source=" & oFile.Path
- On Error Resume Next
- Set rs = cnn.Execute(Sql1)
- arr(m, 1) = rs.Fields(0)
- Set rs = cnn.Execute(Sql2)
- arr(m, 2) = rs.Fields(0)
- Set rs = cnn.Execute(Sql3)
- arr(m, 3) = rs.Fields(0)
- arr(m, 4) = oFile.Name
- End Sub
复制代码
这个代码可以任意扩展多列,多文件,我是用了块状结构化,可以稍微修改即可,使用的是ADO方法,直接把文件夹中的excel表文件当成数据库进行连接,使用cnn.execute+范围进行控制,可以提取单个单元格,或者提取单元格区域 |
|