admin

在MS-Access VBA中查询Excel工作表(使用ADODB记录集)

sql

我想在VBA中查询Excel工作表 指定条件。

简单的查询"SELECT * FROM [PCR$]"可以完美地工作,但是我不知道如何添加WHERE子句。

我尝试过,cmd2.CommandText = "SELECT * FROM [PCR$] WHERE ([B1] IS NOT NULL)"但随后它抱怨缺少参数。

这是完整的代码:

Dim rs2 As New ADODB.Recordset
Dim cnn2 As New ADODB.Connection
Dim cmd2 As New ADODB.Command
Dim intField As Integer
Dim strFile As String

strFile = fncOpenFile
If strFile = "" Then Exit Sub

With cnn2
    .Provider = "Microsoft.Jet.OLEDB.4.0"
    .ConnectionString = "Data Source='" & strFile & "'; " & "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
    .Open
End With

Set cmd2.ActiveConnection = cnn2
cmd2.CommandType = adCmdText
cmd2.CommandText = "SELECT * FROM [PCR$]"
rs2.CursorLocation = adUseClient
rs2.CursorType = adOpenDynamic
rs2.LockType = adLockOptimistic

rs2.Open cmd2

阅读 167

收藏
2021-05-10

共1个答案

admin

在您的连接字符串中,您说

 Excel 8.0;HDR=Yes

这意味着不管第一行包含什么内容,都将被视为标题。如果要使用F1,F2等,请说

Excel 8.0;HDR=No
2021-05-10