VBA, MS Access MS Access в примерах

Текстовые Файлы - Экспорт в текстовый файл в заданной кодировке

По материалам:
http://excelvba.ru/code/SaveTextToFile
http://excelvba.ru/code/encode


Function SaveTextToFile(ByVal txt$, ByVal filename$, Optional ByVal encoding$ = "windows-1251") As Boolean
' функция сохраняет текст txt в кодировке Charset$ в файл filename$
' http://excelvba.ru/code/SaveTextToFile
' http://excelvba.ru/code/encode
'-----------------------------------------------------------------
Dim FSO As Object
Dim ts As Object
Dim binaryStream As Object

On Error Resume Next: Err.Clear
    Select Case encoding$
 
        Case "windows-1251", "", "ansi"
            Set FSO = CreateObject("scripting.filesystemobject")
            Set ts = FSO.CreateTextFile(filename, True)
            ts.Write txt: ts.Close
            Set ts = Nothing: Set FSO = Nothing
 
        Case "utf-16", "utf-16LE"
            Set FSO = CreateObject("scripting.filesystemobject")
            Set ts = FSO.CreateTextFile(filename, True, True)
            ts.Write txt: ts.Close
            Set ts = Nothing: Set FSO = Nothing
 
        Case "utf-8noBOM"
            With CreateObject("ADODB.Stream")
                .Type = 2: .Charset = "utf-8": .Open
                .WriteText txt$
 
                Set binaryStream = CreateObject("ADODB.Stream")
                binaryStream.Type = 1: binaryStream.Mode = 3: binaryStream.Open
                .Position = 3: .CopyTo binaryStream        'Skip BOM bytes
                .flush: .Close
                binaryStream.SaveToFile filename$, 2
                binaryStream.Close
            End With
 
        Case Else
            With CreateObject("ADODB.Stream")
                .Type = 2: .Charset = encoding$: .Open
                .WriteText txt$
                .SaveToFile filename$, 2        ' сохраняем файл в заданной кодировке
                .Close
            End With
    End Select
    SaveTextToFile = Err = 0: DoEvents
End Function



Пример эксплуатации:

'Write
    val = SaveTextToFile(str, stPagePath, "utf-8noBOM")

Назад ToTop
L.E. 06.01.2020
Рейтинг@Mail.ru