Home > How-To Library > Text File Handling
How to write text in a given text file (in three ways)
**************************************************************** * © 2007 CodeItBetter http://www.codeitbetter.com * * This notice MUST stay intact for legal use * **************************************************************** 'Using Non-FSO: Sub WriteTextFileContents(Text As String, filename As String, Optional AppendMode As Boolean) Dim fnum As Integer, isOpen As Boolean On Error GoTo Error_Handler ' Get the next free file number. fnum = FreeFile() If AppendMode Then Open filename For Append As #fnum Else Open filename For Output As #fnum End If ' If execution flow gets here, the file has been opened correctly. isOpen = True ' Print to the file in one single operation. Print #fnum, Text ' Intentionally flow into the error handler to close the file. Error_Handler: ' Raise the error (if any), but first close the file. If isOpen Then Close #fnum If Err Then Err.Raise Err.Number, , Err.Description End Sub Private Sub Command1_Click() Call WriteTextFileContents(Text1.Text, "C:\Temp\Testing.txt") End Sub 'Using FSO: 'Set reference to "Microsoft Scripting Runtime" Public Sub WriteTextFileContentUsingFSO(ByVal sFileName As String, ByVal sText As String) Dim fs As FileSystemObject Dim ts As TextStream Set fs = New FileSystemObject 'To write Set ts = fs.OpenTextFile(sFileName, ForWriting, True) ts.WriteLine sText ts.Close Set ts = Nothing Set fs = Nothing End Sub 'Using Binary mode: Public Sub PutTextToFile(ByVal sFile As String, ByVal sText As String) 'Writes text to file sFile 'Example usage: Call PutTextToFile("C:\Programs.txt", "test") Dim I As Long On Error GoTo PutTextToFile_Error I = FreeFile Open sFile For Binary Access Write Lock Read Write As #I Screen.MousePointer = vbHourglass DoEvents Put #I, , sText On Error GoTo 0 PutTextToFile_Error: Close #I Screen.MousePointer = vbDefault End Sub
If you would like to submit your code here please us. Do not forget to mention your name. We are always thankful to each and everyone of you who submitted their code here.