记录集查询 - Excel

时间:2016-10-19 19:21:24

标签: sql excel vba

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

您好,

我在VBA中的模块内部(代码本身是sourced from here)。我的问题是,我的每个文件中的列从第15行开始,数据从第16行开始。我如何使它成为每个文件,从第15行开始看UNION?

提前致谢!

1 个答案:

答案 0 :(得分:2)

通过ADO或DAO的Excel工作簿SQL查询,您可以通过以时尚方式设置范围来指定工作表的区域:[Sheet$A1:Z2]。首先找到最后一个命名列(调用UNION它们必须是相同的长度和类型)并添加足以进行有效查询的行。下面使用 Z999

strQuery = _
    "SELECT * FROM [Sheet1$A15:Z999] " & _
    "IN '" & ThisWorkbook.Path & "\Source1.xlsx' " & _
    "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
    "UNION " & _
    "SELECT * FROM [Sheet1$A15:Z999] " & _
    "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:Z999] " & _
    "IN '" & ThisWorkbook.Path & "\Source3.xlsx' " & _
    "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
     "ORDER BY A;"