View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
arjen van der wal arjen van der wal is offline
external usenet poster
 
Posts: 24
Default Function to Query CSV file

Hi Jason,

This can be done using ADO and querying the csv file with an SQL statement
as if the csv file was a database table. It requires adding a reference to
ADO in your project. In Visual Basic Editor, go to Tools and then References
and then add a reference to the latest version of Microsoft Active-X Data
Objects Library.

Here's an example adapted from something I created awhile ago based on a
parameter which is entered on a userform with a textbox. There are other ways
to enter the parameter, using a range value or an Input Box, so you may want
to play around with the procedure a bit and fit it to your needs.

Sub QueryTextFile()

Dim EmpNumber As Long
EmpNumber = CLng(frmQuery.txtEmployeeNumber.Value)

Unload frmQuery

Const sConnect As String
sConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Queries\;" & _
"Extended Properties=Text;"

Dim sSql As String
sSql = "SELECT * " & _
"FROM MyFile.csv " & _
"WHERE EmployeeNumber =" & EmpNumber

Dim rsData As ADODB.Recordset
Set rsData = New ADODB.Recordset

rsData.Open sSql, sConnect, adOpenForwardOnly, adLockReadOnly, adCmdText


If Not rsData.EOF Then
Sheet2.Range("A2").CopyFromRecordset rsData
Sheet2.UsedRange.EntireColumn.AutoFit
Else
MsgBox "No Records Returned", vbCritical
End If

rsData.Close
Set rsData = Nothing

End Sub

This example assumes the use of Office 2003. If you're using 2007 then:

sConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Queries\;" & _
"Extended Properties=Text;"

Also note that in the connection string, you just need to put the folder
where the csv file is located. The actual filename goes in the SQL query.