iamnamja
asked on
Querying CSV file through VBA without knowing the header
Hi,
I'm creating a macro that queries a CSV file that a user chooses, and saves the result of only the lines that meet a certain criteria.
The CSV file contains 7 columns, but 2 of which the headers are dates so they vary. I need a way to be able to either find out the header names before running the query, or specify in the query through a header number.
e.g.
My file contains the following CSV file:
Curr,Days,1/1/2013,1/2/201 3,Change,% Change
USD,1,100,100,0,0
JPY,1,1000,1000,0,0
....
Below is my code
I'm creating a macro that queries a CSV file that a user chooses, and saves the result of only the lines that meet a certain criteria.
The CSV file contains 7 columns, but 2 of which the headers are dates so they vary. I need a way to be able to either find out the header names before running the query, or specify in the query through a header number.
e.g.
My file contains the following CSV file:
Curr,Days,1/1/2013,1/2/201
USD,1,100,100,0,0
JPY,1,1000,1000,0,0
....
Below is my code
objConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & dSource & ";" & _
"Extended Properties=""text;HDR=Yes;FMT=Delimited(,)"";Persist Security Info=False"
objConn.Open
SqlQry = "SELECT * FROM " & dfile & " " & _
"WHERE ([% Change] >= 5 OR [% Change] <= -5) "
Rcdset.Open SqlQry, objConn
For i = 0 To Rcdset.Fields.Count - 1
data_ws.Cells(1, i + 1).Value = Rcdset.Fields(i).Name
Next i
data_ws.Cells(2, 1).CopyFromRecordset Rcdset
So basically I'm looking for anything that has a 5% change, and I also need to look for any that didn't have data on today's column. So in this case, it would be WHERE 1/2/2013 = '' but how can I chose this column/header when the value is constantly going to change?
Are the fields always in the same order? If so, perhaps specify HDR=No in the connection and use F4 for today's field and F6 for the % change field. Then you just need to skip the first record in your processing.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks while waiting, I did just this... I queried it twice. Once to get the header, and once to use the header to query it. Thanks!
Sorry I took seven minutes to reply! ;)