"定义了太多字段"使用ADO查询Excel时

时间:2014-01-11 01:01:51

标签: sql vba excel-vba ado adodb

我正在使用以下ADO查询Excel 2010工作簿:

Function WorksheetRecordsetSQL(workbookPath As String, sheetName As String, selectSQL As String) As ADODB.Recordset

Dim objconnection As New ADODB.Connection
Dim objrecordset As New ADODB.Recordset

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1

objconnection.CommandTimeout = 99999999

objconnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=" & workbookPath & ";" & _
        "Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"";"

objrecordset.Open selectSQL, _
    objconnection, adOpenStatic, adLockOptimistic, adCmdText

Set WorksheetRecordsetSQL = objrecordset

End Function

当我用这个SQL调用它时:

Select * FROM [someWorksheet$]

该功能成功执行。但如果我把它称为:

Select *,cdate(someField) FROM [someWorksheet$]

然后我收到了这个错误:

Too many fields defined.

我发现select *查询产生的记录集包含255个字段(Access引擎在查询中可以拥有的最大值),即使工作表中只有58列。因此,一个额外的cdate()列会重载引擎并产生错误。

有没有办法让select *查询从Excel工作表中获取空白列?或者我可以设置一些允许超过255个字段的参数?

1 个答案:

答案 0 :(得分:3)

您可以指定应该阅读的范围,以便减少进入查询的列数。这里从单元格A1到列BF(58)所有行:

  

FROM [Source_sheet $ A1:BF]

Sub main()
    Dim reultingRecordset As ADODB.Recordset

    Set reultingRecordset = WorksheetRecordsetSQL( _
        "C:\Temp\VBA\ReadWithADOSource.xlsx", _
        "Source_sheet", _
        "Select * FROM [Source_sheet$]")

    Debug.Print "Select * FROM [Source_sheet$] >"
    Debug.Print "Fields: " & reultingRecordset.Fields.Count & " Records: " & reultingRecordset.RecordCount

    Set reultingRecordset = WorksheetRecordsetSQL( _
        "C:\Temp\VBA\ReadWithADOSource.xlsx", _
        "Source_sheet", _
        "Select *,cdate(Col2) FROM [Source_sheet$A1:BF]")

    Debug.Print "Select *,cdate(Col2) FROM [Source_sheet$A1:BC] > "
    Debug.Print "Fields: " & reultingRecordset.Fields.Count & " Records: " & reultingRecordset.RecordCount

End Sub

<强>输出:

选择*来自[Source_sheet $]&gt;
字段:255条记录:8

选择*,cdate(Col2)FROM [Source_sheet $ A1:BC]&gt;
字段:59记录:8