| This module opens or save plain text to a file: Option Explicit 'Declare all variables 'Enumerations for the type of output wanted Public Enum OutputModeConsts Add = 0 'Append to the current text file OverWrite = 1 'Overwrite any existing text in the file End Enum Public Function OpenText(ByVal Filename As String) As String On Error GoTo ErrorHandler Dim FileNumber As Integer Dim TempText As String 'Find a free file number FileNumber = FreeFile 'Open the file for input Open Filename For Input As #FileNumber 'Return the file's contents OpenText = Input(LOF(FileNumber), FileNumber) 'Close the file Close #FileNumber 'Exit the function so as not cause an error Exit Function ErrorHandler: Dim Answer As VbMsgBoxResult 'Close the file in case it is open Close #FileNumber 'Tell the user the error and ask if another method of opening should be tried Answer = MsgBox("Sorry the file could not be opened." & vbNewLine & _ "Details: " & Err.Number & " - " & Err.Description & vbNewLine & vbNewLine & _ "Would you like to try opening the file using another method?" & vbNewLine & _ "The results may not be accurate", vbCritical + vbYesNo + vbDefaultButton2, "Error") 'If yes If Answer = vbYes Then 'Open the file Open Filename For Input As #FileNumber 'Read each individual line Do While Not EOF(FileNumber) 'Input file to temp variable Input #FileNumber, TempText 'Return text + new line of text OpenText = OpenText & TempText & vbCrLf 'vbNewLine Loop 'Close the file Close #FileNumber End If End Function Public Sub SaveText(ByVal Filename As String, ByVal TextToSave As String, _ Optional ByVal OutputMode As OutputModeConsts = OverWrite) On Error GoTo ErrorHandler Dim FileNumber As Integer FileNumber = FreeFile 'If the FileName is not "" If Filename <> "" Then If OutputMode = OverWrite Then 'Open the for output Open Filename For Output As #FileNumber 'Write the text to the file Print #FileNumber, TextToSave 'Close the file Close #FileNumber ElseIf OutputMode = Add Then 'Open the for output Open Filename For Append As #FileNumber 'Write the text to the file Print #FileNumber, TextToSave 'Close the file Close #FileNumber End If End If 'Exit the sub so as not to cause an error Exit Sub ErrorHandler: 'Close the file in case it is open Close #FileNumber 'Tell the user the error MsgBox "Sorry the file could not be saved." & vbNewLine & _ "Details: " & Err.Number & " - " & Err.Description, _ vbCritical + vbOKOnly, _ "Error" End Sub To use type something like: Text1.Text = OpenText("C:\My Documents\New Text File.txt") Or: Call SaveText("C:\My Documents\New Text File.txt", Text1.Text) Call SaveText("C:\My Documents\New Text File.txt", Text1.Text, Add) Etc. |
Opening & Saving Text Files |
Express News India | Freelance ecommerce web development India