Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Excel worksheet in MS-Access VBA (using ADODB recordset)

I'd like to query an Excel worksheet in VBA and specify conditions.

The simple query "SELECT * FROM [PCR$]" works perfectly, but I don't know how to add a WHERE clause.

I tried cmd2.CommandText = "SELECT * FROM [PCR$] WHERE ([B1] IS NOT NULL)" but then it complains about missing parameters.

This is the complete code:


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
like image 991
skerit Avatar asked Jan 18 '10 13:01

skerit


People also ask

What is Adodb recordset in VBA?

The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields). In ADO, this object is the most important and the one used most often to manipulate data from a database.

What is Adodb connection in VBA?

The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database. If you want to access a database multiple times, you should establish a connection using the Connection object.


2 Answers

In your connection string you say

 Excel 8.0;HDR=Yes

Which means that the first row will be treated as the header, no matter what it contains. If you want to use F1, F2 etc, say

Excel 8.0;HDR=No
like image 145
Fionnuala Avatar answered Sep 18 '22 13:09

Fionnuala


Because you have the HDR=Yes option, the column name should be the data in the first row.

http://support.microsoft.com/kb/316934

like image 32
bryanjonker Avatar answered Sep 21 '22 13:09

bryanjonker