|
|
Текстовые файлы - запись, дозапись и чтение (FSO)
Option Compare Database
Option Explicit
Public Sub TextOutputAsTXT(sTXTPath$, sText$)
Dim fso As Object
Dim ts As Object
On Error GoTo TextOutputAsTXT_Err
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.CreateTextFile(sTXTPath, True, False)
ts.Write sText
ts.Close
TextOutputAsTXT_Bye:
On Error Resume Next
Set ts = Nothing: Set fso = Nothing
Exit Sub
TextOutputAsTXT_Err:
MsgBox "Ошибка " & Err.Number & vbCrLf & Err.Description & vbCrLf & _
"в процедуре: TextOutputAsTXT", vbCritical, "Error!"
Resume TextOutputAsTXT_Bye
End Sub
Public Sub TextOutputAddText(sTXTPath$, sText$)
Dim fso As Object
Dim ts As Object
On Error GoTo TextOutputAddText_Err
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(sTXTPath, 8, True): ts.Write sText: ts.Close
Set ts = Nothing: Set fso = Nothing
TextOutputAddText_Bye:
On Error Resume Next
Set ts = Nothing: Set fso = Nothing
Exit Sub
TextOutputAddText_Err:
MsgBox "Ошибка " & Err.Number & vbCrLf & Err.Description & vbCrLf & _
"в процедуре: TextOutputAddText", vbCritical, "Error in module modTextOutput"
Resume TextOutputAddText_Bye
End Sub
Public Function TextReadFromFile(sTXTPath$) As String
Dim fso As Object
Dim ts As Object
On Error GoTo TextReadFromFile_Err
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(sTXTPath, 1, True): TextReadFromFile = ts.ReadAll: ts.Close
TextReadFromFile_Bye:
On Error Resume Next
Set ts = Nothing: Set fso = Nothing
Err.Clear
Exit Function
TextReadFromFile_Err:
MsgBox "Ошибка " & Err.Number & vbCrLf & Err.Description & vbCrLf & _
"в процедуре: TextReadFromFile", vbCritical, "Error in module modTextOutput"
Resume TextReadFromFile_Bye
End Function
Пример эксплуатации:
Private Sub TestTXTfile()
Dim sPath$
Dim str$
sPath = "d:\Temp\TempTest01.txt"
str = "01 - Записали ..." & vbCrLf
TextOutputAsTXT sPath, str
str = "02 - Дописали" & vbCrLf
TextOutputAddText sPath, str
str = "03 - Прочитали ..."
TextOutputAddText sPath, str
str = TextReadFromFile(sPath)
Debug.Print "---------------------" & vbCrLf & _
"Файл: " & sPath & vbCrLf & _
"Содержит строки:" & vbCrLf & "---------------------" & _
vbCrLf & str & vbCrLf & "---------------------"
End Sub
|
|