VBA - Check CSV file format without opening file?

ShawnPCooke

Board Regular
Joined
May 14, 2007
Messages
151
I'm automating the import of a particularly large CSV file. This file is generated by the user, and I want to validate that it is in the correct format (column order & names) before continuing the macro.

Ideally, I'd like to read the header row from the file before committing to opening the whole thing. Is there a way in VBA to read the first N characters from a text file before opening the whole file?

I already tried opening the file for text I/O, and just reading the first line, but that took longer than just importing the thing.

Thank you!
 

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.
Never mind... I figured it out myself. For those who come after me, here's how I did it.

First, I made a reference to Microsoft Scripting Runtime. That gave me access to the FileSystemObject object and the TextStream object.

Code:
Dim fso as FileSystemObject
Dim txtStream as TextStream
Dim strFilename as string
Dim strText as string

strFilename = "C:\filepath-goes-here"
Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(strFilename, ForReading, False)
strText = txtStream.ReadLine
txtStream.Close

The first line was then contained in strText, and I could check that. Runs super quick.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,903
Messages
6,175,279
Members
452,630
Latest member
OdubiYouth

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