简体   繁体   English

如果工作表的第一行没有列名,如何使用ADODB连接从Excel检索数据?

[英]How to retrieve data from Excel with ADODB connection if the first line of the worksheet does not have the column name?

I use the following type of code to retrieve data from some Excel Workbooks (path is a Parameter) 我使用以下类型的代码从一些Excel工作簿中检索数据(路径是参数)

Dim strSQL  As String, conStr as String
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset


conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & path & "';" & _
             "Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;"";"

strSQL = "SELECT [Field1], [Field2] FROM [Worksheet$] WHERE [Thing1] > 1"

cnn.open conStr   
rs.Open query, cnn, adOpenStatic, adLockOptimistic, adCmdText

That code works fine if the names of the fields are on the first row of the worksheet. 如果字段的名称位于工作表的第一行,则该代码可以正常工作。 The problem is that I need to retrieve data from a worksheet that the data table begins on another row (Row 10). 问题是我需要从工作表中检索数据表从另一行开始的数据(第10行)。

Is there a way to specify the first row of my data table? 有没有办法指定数据表的第一行?

See this Microsoft page . 请参阅此Microsoft页面 You can use something like: 您可以使用以下内容:

strSQL = "SELECT [Field1], [Field2] FROM [Worksheet$$A10:B43] WHERE [Thing1] > 1"

Use a named or unnamed range in your query: 在查询中使用命名或未命名范围:

strQuery = "SELECT * FROM MyRange"

strQuery = "SELECT * FROM [Sheet1$A1:B10]"

See these Microsoft support articles for more information: 有关更多信息,请参阅这些Microsoft支持文章:

How To Use ADO with Excel Data from Visual Basic or VBA 如何将ADO与Visual Basic或VBA中的Excel数据一起使用

ExcelADO demonstrates how to use ADO to read and write data in Excel workbooks ExcelADO演示了如何使用ADO在Excel工作簿中读取和写入数据

You can query a range of cells starting from row 10: 您可以从第10行开始查询一系列单元格:

 "SELECT * FROM [Worksheet$A10:S100] WHERE [Thing1] > 1"

What can be tough is finding what the end of the range should be. 什么是艰难的是找到范围的终点应该是什么。 You could put in a ridiculously large number, but then you'd have to add special handling for the rows of NULL at the end. 你可以输入一个非常大的数字,但是你必须在最后为NULL行添加特殊处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM