Open/Read file in Vb

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

is it possible to open and read txt files in vba? the files im reading arent
to be used as imports for tables, they just contain text that i need to
search.

thanks for any help
ben
 
Ben said:
is it possible to open and read txt files in vba? the files im
reading arent to be used as imports for tables, they just contain
text that i need to search.

VB has built-in I/O support; look up the Open, Input, and Close
statements, and the Input() and FreeFile() functions, in the VB online
help.

Here's a simple example to read the complete contents of a file (no more
than 2GB in size) into a String variable:

Dim strFileName As String
Dim strFileText As String
Dim intFileNo As Integer

strFileName = "C:\Temp\TestReport.txt"

intFileNo = FreeFile()
Open strFileName For Input As #intFileNo
strFileText = Input(LOF(intFileNo), intFileNo)
Close #intFileNo

Note: you can also use methods from the Microsoft Scripting Library to
do this sort of thing, but for simple I/O, using the native methods is
more efficient and reliable.
 
Ben said:
is it possible to open and read txt files in vba? the files im reading
arent
to be used as imports for tables, they just contain text that i need to
search.

The usual BASIC syntax works in VBA in Access

Open "myfile.txt" For Input As #1
Do While Not Eof(1)
Line Input #1, a$
Loop

will work.
 
Never a good idea to hard code the file number:

Dim intFile As Integer
Dim strInput As String

intFile = FreeFile()
Open "myfile.txt" For Input As #intFile
Do While Not Eof(intFile)
Line Input #intFile, strInput
Loop
Close #intFile
 
Back
Top