VBA Import CSV File with different field types in various orders

jaysunice

New Member
Joined
Jan 13, 2011
Messages
12
I'd like to import a CSV file with VBA.

  • Some of the columns should be formatted as text (i.e., numbers with leading or trailing zeros such as ZIP codes), others as numbers, some as dates, and others should be skipped.
  • I know the proper data type by looking at the header row name, however, the order of the columns is not always the same upon import -- so it's not as easy as saying, column 1 = text, column 2 = number, etc... because they will come in differently.
The long way (I can think of): import csv, delete all but header row, determine data type, re-import csv with proper data type.

Is there a way to do this on-the-fly? I recorded the "Text Import Wizard" and it's a good start, but I'm getting lost on how to assign scan the header row (1st row) prior to assignment of the data type.
 

Excel Facts

Does the VLOOKUP table have to be sorted?
No! when you are using an exact match, the VLOOKUP table can be in any order. Best-selling items at the top is actually the best.
You could use a little function like this one adapted from cpearson.com:
Code:
Sub test()
xxx = ReadHeaders("C:\Users\jaysunice\Documents\File.csv")
yyy = Split(xxx, ",")
End Sub

Function ReadHeaders(FName As String)
X = FreeFile
Open FName For Input Access Read As #X
If Not EOF(1) Then Line Input #X, ReadHeaders
Close #X
End Function
which reads the first line of a text file. You could then split it as in the commented out line and you have, if it's a proper comma separated variable file, an array of headers to plough through.
 
Last edited:
Upvote 0
There is a serious error:
If Not EOF(1) Then Line Input #X, ReadHeaders
should read:
If Not EOF(X) Then Line Input #X, ReadHeaders
 
Upvote 0

Forum statistics

Threads
1,223,789
Messages
6,174,576
Members
452,573
Latest member
Cpiet

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top