View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
onedaywhen onedaywhen is offline
external usenet poster
 
Posts: 459
Default Querying a CSV file from Excel

ExcelMonkey wrote ...

Is it possible to query data in a CSV file (i.e. text
file) from VBA into Excel?


Yes. If you prefer VBA code you can use ADO with the MS OLEDB provider
for Jet, specifying Text in the extended properties e.g. this
connection string

Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Tempo\;
Extended Properties='Text;HDR=Yes'

applies to all comma-delimited text files (other delimiters or fixed
width text requires a scheme.ini file) in the folder specified. To
query use the filename as a table name e.g.

SELECT ID, lanme, fname FROM MyFile#txt

Because the folder is the 'database' you can create joins between
files e.g.

SELECT T1.ID, T1.lanme, T1.fname
FROM MyFile#txt T1
INNER JOIN MyFile#txt T2
ON T1.ID = T2.ID

You can use the Jet provider to create text files:

CREATE TABLE MyNewFile#txt
(
ID INTEGER,
lname VARCHAR(35),
fname VARCHAR(35)
)
;
INSERT INTO MyNewFile#txt
(ID, lname, fname)
VALUES (1, 'day', 'when')
;

One thing that won't work while *connected* to a 'Text' Jet connection
(as above), but will work if connected to, say, an 'Excel 8.0' Jet
connection, is the following syntax e.g. to create a new text file
based on data from an Excel workbook:

SELECT ID, lanme, fname
INTO [Text;C:\Tempo\;].ANewFile#txt
FROM [Excel 8.0;database=C:\Tempo\db.xls].[PersonalDetails$]

Should you prefer GUI tools you can use MS Query with an ODBC text
driver. The approach is largely the same. Here is a detailed
description for tab delimited (i.e. schema.ini file required):

http://groups.google.com/groups?selm...g. google.com

--