Top.Mail.Ru
Ответы
Аватар пользователя
5 лет назад
от
Изменено

Чтение текстовых файлов с помощью Excel VBA

Как считать текстовый файл с помощью Excel VBA? В большинстве источников пишут про System.IO.StreamReader, но у меня скрипт не видит библиотеку System.IO.

Только авторизированные пользователи могут оставлять свои ответы
Дата
Популярность
Аватар пользователя
Новичок
5лет

https://stackoverflow.com/questions/11051964/vba-readline-error-while-reading-from-a-file

Sub m1()
Dim TextLine
Open "file.txt" For Input As #1
Do While Not EOF(1) ' Loop until end of file.
Line Input #1, TextLine ' Read line into variable.
Debug.Print TextLine ' Print to the Immediate window.
Loop
End Sub

Аватар пользователя
Мудрец
5лет

Как еще один вариант: использовать объект fso
Чтение текстового файла в переменную:

Function ReadTXTfile(ByVal filename As String) As String
Set fso = CreateObject("scripting.filesystemobject")
Set ts = fso.OpenTextFile(filename, 1, True): ReadTXTfile = ts.ReadAll: ts.Close
Set ts = Nothing: Set fso = Nothing
End Function

Запись в текстовый файл из переменной:

Function SaveTXTfile(ByVal filename As String, ByVal txt As String) As Boolean
On Error Resume Next: Err.Clear
Set fso = CreateObject("scripting.filesystemobject")
Set ts = fso.CreateTextFile(filename, True)
ts.Write txt: ts.Close
SaveTXTfile = Err = 0
Set ts = Nothing: Set fso = Nothing
End Function

Добавление в текстовый файл из переменной:

Function AddIntoTXTfile(ByVal filename As String, ByVal txt As String) As Boolean
On Error Resume Next: Err.Clear
Set fso = CreateObject("scripting.filesystemobject")
Set ts = fso.OpenTextFile(filename, 8, True): ts.Write txt: ts.Close
Set ts = Nothing: Set fso = Nothing
AddIntoTXTfile = Err = 0
End Function