How can I get all the lines of text from a .txt file and save them to a string variable? Also, If I put this string variable into a different .txt file later on, will the words still be formatted correctly on their proper lines etc.?
Printable View
How can I get all the lines of text from a .txt file and save them to a string variable? Also, If I put this string variable into a different .txt file later on, will the words still be formatted correctly on their proper lines etc.?
You can use the above function like this:VB Code:
Public Function ReadFile(ByVal sFileName As String) As String Dim hFile As Integer On Error Resume Next 'Get a free file handle hFile = FreeFile 'Open the file Open sFileName For Input As #hFile 'read the whole content and return it ReadFile = Input(LOF(hFile), hFile) 'Close the file Close #hFile End FunctionYes, if you save this text string (without changing it) you have made a copy of the origional file.VB Code:
Dim sText As String sText = ReadFile("c:\thePath\theFile.txt")Here's an example:VB Code:
Public Sub SaveFile(ByVal sFileName As String, ByVal sText As String) Dim hFile As Integer On Error Resume Next hFile = FreeFile Open sFileName For Output As #hFile Print #hFile, sText; Close #hFile End SubVB Code:
Dim sTxt As String 'read the content of one (existing) file sTxt = ReadFile("c:\FirstFile.txt") 'save this to another file Call SaveFile("c:\SecondFile.txt", sTxt)
Here ksi a quick sample for you:
VB Code:
Private Sub Command1_Click() Dim strText$, i% Dim arLines() As String Open "c:\temp\test.txt" For Input As #1 'read entire file into string variable strText = Input(LOF(1), #1) 'split text on each carriage return arLines = Split(strText, vbNewLine) 'read each line For i = 0 To UBound(arLines) Debug.Print arLines(i) Next i Close #1 End Sub