How to write text in a given text file (in three ways)
Posted on August 1, 2011
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | 'Text File Handling - How to write text in a given text file (in three ways) '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, ByRef sText As String, Optional ByVal blnAppend As Boolean = True) '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 If blnAppend Then Put #I, LOF(I) + 1, sText Else Put #I, , sText End If ExitHere: On Error GoTo 0 PutTextToFile_Error: Close #I Screen.MousePointer = vbDefault End Sub |