使用SQL查询循环访问文件夹

时间:2016-10-20 14:04:21

标签: mysql sql vba excel-vba excel

strQuery = _
     "SELECT * FROM [Sheet1$A15:E999] " & _
     "IN '" & ThisWorkbook.Path & "\Source1.xlsx' " & _
     "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;ExtendedProperties='HDR=YES;'] " & _
     "UNION " & _
     "SELECT * FROM [Sheet1$A15:E999] " & _
     "IN '" & ThisWorkbook.Path & "\Source2.xlsx' " & _
     "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
     "UNION " & _
     "SELECT * FROM [Sheet1$A15:E999] " & _
     "IN '" & ThisWorkbook.Path & "\Source3.xlsx' " & _
     "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
     "ORDER BY A;"

早上好,

我有一个最后的指甲继续这个编码我有任何帮助非常感谢。我从单个文件夹收集大量文件,文件名不同(尽管数据顺序和数据相同)。

问题是:

  • 是否可以通过'strQuery'获取所有文件而不会降低代码速度?我该如何继续这样做? (例如:我认为可能循环但可能会减速? - 见下文)
  • 是否可以一次读取(比方说)100个excel文件数据? (虽然我不知道它的名字?)

我可以修改strQuery(通过为它分配一个文本字符串)并输入一个循环来遍历每个文件,但是我要重新调查这需要我为每个文件而不是一次创建一个连接?

感谢任何帮助!

提前致谢。

-

下面的完整代码(我不知道在哪里以可见的方式放置它)

Sub SqlUnionTest()

Dim strConnection As String
Dim strQuery As String
Dim objConnection As Object
Dim objRecordSet As Object, qText As String

strConnection = _
    "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "User ID=Admin;" & _
    "Data Source='" & ThisWorkbook.FullName & "';" & _
    "Mode=Read;" & _
    "Extended Properties=""Excel 12.0 Macro;"";"


Dim sFile As String

sFile = Dir(ThisWorkbook.Path & "\*.xlsx")

Do While sFile <> ""

    strQuery = _
     "SELECT * FROM [Sheet1$A15:E999] " & _
     "IN '" & ThisWorkbook.Path & "\" & sFile & _
     "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;ExtendedProperties='HDR=YES;'] " & _
     "UNION "

    sFile = Dir()

Loop

strQuery = Left(strQuery, Len(strQuery) - 7) 'to remove last UNION which is not necessary

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open strConnection
Set objRecordSet = objConnection.Execute(strQuery)
RecordSetToWorksheet Sheets(1), objRecordSet
objConnection.Close

End Sub

Sub RecordSetToWorksheet(objSheet As Worksheet, objRecordSet As Object)

Dim i As Long

With objSheet
    .Cells.Delete
    For i = 1 To objRecordSet.Fields.Count
        .Cells(1, i).Value = objRecordSet.Fields(i - 1).Name
    Next
    .Cells(2, 1).CopyFromRecordset objRecordSet
    .Cells.Columns.AutoFit
End With

End Sub

1 个答案:

答案 0 :(得分:1)

您可以使用DIR()函数循环浏览文件夹中的所有.xlsx文件,而无需知道具体的文件名。如果你需要清除任何文件,你可以在循环中放置条件测试。

代码未经测试

Dim sFile As String, strQuery As String

sFile = Dir(ThisWorkbook.Path & "\*.xlsx")

Do While sFile <> ""

    strQuery = strQuery & _
     "SELECT * FROM [Sheet1$A15:E999] " & _
     "IN '" & ThisWorkbook.Path & "\" & sFile & _
     "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;ExtendedProperties='HDR=YES;'] " & _
     "UNION;"

    sFile = Dir()

Loop

strQuery = Left(strQuery, Len(strQuery) - 7) 'to remove last UNION which is not necessary