美文网首页
Vba+Sql汇总多工作簿多工作表

Vba+Sql汇总多工作簿多工作表

作者: shengjiaimi | 来源:发表于2018-04-19 17:24 被阅读0次

    Sub 多工作簿工作表汇总()

        Dim Cnn As Object, Rst As Object, Rs As Object, FilePath$, FullName$, FullPath$, Sql$, Sht_Name$, i&

        Set Cnn = CreateObject("ADODB.Connection")

        Set Rst = CreateObject("ADODB.Recordset")

        FilePath = ThisWorkbook.Path

        FullName = Dir(FilePath & "\*.xls*")

        Do While FullName <> ""

            If FullName <> ThisWorkbook.Name Then

                FullPath = FilePath & "\" & FullName

                Cnn.Open "Provider=Microsoft.Ace.Oledb.12.0;Extended Properties=Excel 12.0;Data Source=" & FullPath

                Set Rst = Cnn.OpenSchema(20)

                Do Until Rst.EOF

                    Sht_Name = Rst("TABLE_NAME").Value

                    If Sql = "" Then

                        Sql = "select * from [" & FullPath & "].[" & Sht_Name & "]"

                    Else

                        Sql = Sql & " Union all select * from [" & FullPath & "].[" & Sht_Name & "]"

                    End If

                    Rst.MoveNext

                Loop

                Rst.Close

                Cnn.Close

            End If

            FullName = Dir

        Loop

        Cnn.Open "Provider=Microsoft.Ace.Oledb.12.0;Extended Properties=Excel 12.0;Data Source=" & ThisWorkbook.FullName

        Set Rs = Cnn.Execute(Sql)

        For i = 0 To Rs.Fields.Count - 1

            Cells(1, i + 1).Value = Rs.Fields(i).Name

        Next i

        [a2].CopyFromRecordset Rs

        Cnn.Close

        Set Rs = Nothing

        Set Rst = Nothing

        Set Cnn = Nothing

    End Sub

    相关文章

      网友评论

          本文标题:Vba+Sql汇总多工作簿多工作表

          本文链接:https://www.haomeiwen.com/subject/dszwkftx.html