1

我知道我必须设置 HDR=NO 以便将标题包含在结果中。但是当我设置它时,我不能在 SQL 语句中使用 where。任何解决方法的想法;

Sub adoExcel()

Set objConnection = CreateObject("ADODB.Connection")
Set objrecordset = CreateObject("ADODB.Recordset")

'*************************************************************************************
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Users\sp\Desktop\test ado excel\test.xls;" & _
"Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"
'*************************************************************************************
'where Number =2
objrecordset.Open "Select * FROM [Sheet1$] where Number =1", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText

ActiveSheet.Cells(2, 1).CopyFromRecordset objrecordset

'*************************************************************************************
' Loop through the recordset and send data to the Immediate Window
'**************************************************************************************
'objrecordset.MoveFirst

'Do
   ' Debug.Print objrecordset![Name] & " " & objrecordset![Number]
   ' objrecordset.MoveNext
'Loop Until objrecordset.EOF

'**************************************************************************************
'ActiveSheet.Cells(1, 1).CopyFromRecordset objrecordset![Name] & " " & objrecordset![Number]
'*************************************
End Sub
4

1 回答 1

0

当您使用 HDR=NO 时,您的字段将使用 F1、F2 等隐式引用。因此,如果您的数据如下所示:

  A      B
1 Name   Number
2 John   100
3 Matt   200

您之前的查询:

Select ... from [Sheet1$] where Number = "200"

看起来像

Select ... from [Sheet1$] where [F2] = "200"

您的代码将如下所示:

Sub adoExcel()

    Set objConnection = CreateObject("ADODB.Connection")
    Set objrecordset = CreateObject("ADODB.Recordset")

    objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Users\sp\Desktop\test ado excel\test.xls;" & _
        "Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"

    ' Notice that I have placed 200 in quotations assuming Text information
    ' Import Export Mode (IMEX) is set to mixed-type (value of 1)
    ' Also, field name used in WHERE clause is F2
    objrecordset.Open "Select * FROM [Sheet1$] where [F2]= ""200""", objConnection

    objrecordset.MoveFirst
    Do
        ' Notice the use of Fields F1 and F2
        Debug.Print objrecordset![F1] & " " & objrecordset![F2]
        objrecordset.MoveNext
    Loop Until objrecordset.EOF

End Sub

参考:HDR=0 时的隐式字段名称IMEX 属性

于 2013-09-14T19:45:39.683 回答