advertisement

Find Code  Advanced Search   

Free Newsletters:   
browse free vb code
Submit Code
ASP,  HTML, and XML
Database
Dates  and Math
Files  and Directories
Forms  and Controls
Lists,  Collections, and Arrays
Miscellaneous
Multimedia/Games
Office/VBA
Network/Internet
Registry
Screen/Graphics
String  Manipulation
System/API
Windows  2000/XP
VB.NET/ASP.NET



advertisement
Read Text Files Into a Recordset

Author: Narender Patlolla
Category: Files and Directories
Type: Snippets
Difficulty: Beginning

Version Compatibility:  Visual Basic 5   Visual Basic 6  

More information: This code shows you how to use ADO and the ODBC text driver to open a text file an read it into a recordset. There are two connection strings. The first shows you how to read the file as if there are no headers (i.e., the first row is not treated as column names). The second shows you how to treat the first row as a header. Included are sample data which you can save to a test file to see how it works. A reference to Microsoft's Active Data Objects is required.

This code has been viewed 121532 times.

Instructions: Copy the declarations and code below and paste directly into your VB project.


Declarations:

'(None)

Code:

Dim connCSV As New ADODB.Connection
Dim rsTest As New ADODB.Recordset
Dim adcomm As New ADODB.Command
Dim path As String

path = "C:\Testdir\"  'Here Test dir is the Directory where
' the text file is located. don't write the file name here.

'This is connection for a text file without Header

 'connCSV.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
 & path & ";Extended Properties='text;HDR=NO;FMT=Delimited'"


'This is connection for a text file with Header (i.e., columns
 
connCSV.Open "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
& path & ";Extensions=asc,csv,tab,txt;HDR=NO;Persist Security Info=False"
    
    
   rsTest.Open "Select * From test.txt", _
       connCSV, adOpenStatic, adLockReadOnly, adCmdText
Do While Not rsTest.EOF
MsgBox rsTest(0)   'You can select the required data
rsTest.movenext
Loop

'IF YOU WANT TO TEST THIS,
'SAVE THE FOLLOWINT TO C:\TESTDIR\TEST.TXT
'AND RUN THE ABOVE CODE WITH THE TWO DIFFERENT
'CONNECTION OPEN STATEMENTS

'Name,Address,City,State,Zip
'John , Doe, NY, NY, 910

Text Boxes

Sponsored Links