What code can I use to load all the text from a text file into a variable?
Printable View
What code can I use to load all the text from a text file into a variable?
' Open file for input.
Open "TESTFILE" For Input As #1
' Loop until end of file.
Do While Not EOF(1)
' Read data into two variables.
Input #1, MyString
' Print data to Debug window.
Debug.Print MyString
Loop
' Close file.
Close #1
If you want to load the entire text file into one single string, you might want this code:
Use the LoadFile function like this to load your AUTOEXEC.BAT for example:Code:Option Explicit
Function LoadFile(Filename As String) As String
'*** Dimension local variables...
Dim fileNum As Integer ' file number
Dim fileLen As Long ' file length
Dim fileData As String ' file data
fileNum = FreeFile ' get file handle
Open Filename For Binary As #fileNum ' open file
fileLen = LOF(fileNum) ' get file length
fileData = Space$(fileLen) ' set buffer size
Get #fileNum, , fileData ' read file data
Close #fileNum ' close file
LoadFile = fileData ' return value
End Function
Notice that this function will load info from ANY file into the string variable, i.e. executable files, graphics files, text files, wave files, you name it.Code:Dim myFile As String
myFile = LoadFile("c:\autoexec.bat")
Hope this helps.
Two methods I've used in the past...
Code:Dim inFile&, lne$, text$
inFile = FreeFile
Open "c:\file.dat" for Input as inFile
Line Input #inFile, text
While Not EOF(inFile)
Line Input #inFile, lne
text = text + vbCrLf + lne
Wend
Close inFile
Code:Dim inFile&, text$
inFile = FreeFile
Open "c:\file.dat" for Input as inFile
text = Input(LOF(inFile), #inFile)
Close inFile
This one's even faster! :p :p
Code Snippet below:
-------------------
Option Explicit
Private Sub Command1_Click()
'Load Text from file (Filename: MyFile.txt)
Open App.Path & "\MyFile.txt" for input as #1
Text1.Text = Input(LOF(1), #1)
Close
End Sub
-------------------
A line of code does the trick. :p :p
You can do a search on the word 'input' in MSDN and click on 'Input Function'. The code syntax will be shown. Hope this helps! :)