Excel vba line input

Чтение и запись в файл, открытый с помощью оператора Open. Операторы Input, Line Input, Write и функция EOF. Примеры использования в VBA Excel.

Операторы чтения и записи в файл

Оператор Input #

Оператор Input # считывает данные из открытого файла с последовательным доступом и присваивает эти данные переменным.

Оператор Input # используется только с файлами, открытыми в режиме Input или Binary. При прочтении стандартные строковые или числовые значения присваиваются переменным без изменения.

Синтаксис оператора Input #:

Input #Номер_файла, Переменные

Компоненты оператора Input #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Переменные – обязательный параметр, представляющий из себя список переменных, разделенных запятой, которым присваиваются значения, считанные из файла.

Особенности применения оператора Input #:

  • Элементы данных в файле должны быть указаны в том же порядке, что и переменные в списке Переменные, и соответствовать им по типу данных. Если переменная числовая, а данные текстовые, этой переменной будет присвоено нулевое значение.
  • Если при чтении данных достигнут конец файла, чтение прерывается и возникает ошибка. Для ее предупреждения в коде VBA Excel используется функция EOF.
  • Чтобы данные из файла могли быть правильно прочитаны и записаны в переменные с помощью оператора Input #, они должны быть записаны в файл с помощью оператора Write #. Он обеспечивает правильное разделение каждого из полей (элементов) данных.

Оператор Line Input #

Оператор Line Input # считывает одну строку из открытого файла с последовательным доступом и присваивает ее значение строковой переменной.

Оператор Line Input # считывает из файла по одному символу до тех пор, пока не встретится символ возврата каретки (Chr(13)) или последовательность символа возврата каретки и перевода строки (Chr (13) + Chr(10)).

Синтаксис оператора Line Input #:

Line Input #Номер_файла, Переменная

Компоненты оператора Line Input #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Переменная – обязательный параметр, представляющий из себя имя переменной, объявленной как String или Variant, которой присваивается строка, считанная из файла.

Оператор Write #

Оператор Write # записывает данные в файл с последовательным доступом.

Синтаксис оператора Write #:

Write #Номер_файла, [Данные]

Компоненты оператора Write #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Данные – необязательный параметр, представляющий из себя одно или несколько числовых или строковых выражений, разделенных запятой, которые нужно записать в файл.

Особенности применения оператора Write #:

  • Данные, записанные с помощью оператора Write #, считываются из файла с помощью оператора Input #.
  • Если опустить параметр Данные и добавить запятую после Номер_файла, в файл будет добавлена пустая строка.
  • Несколько выражений в списке Данные могут быть разделены точкой с запятой или запятой.
  • Числовые данные всегда записываются с точкой в качестве разделителя целой и дробной части.
  • Оператор Write # вставляет запятые между элементами и прямые парные кавычки вокруг строк при их записи в файл.
  • После записи в файл последнего символа из параметра Данные оператор Write # вставляет символы возврата каретки и перевода строки (Chr (13) + Chr(10)).

Функция EOF

Функция EOF возвращает логическое значение True, когда достигнут конец файла, открытого для последовательного (Input) или произвольного (Random) доступа.

Синтаксис функции EOF:

Номер_файла – это номер, присвоенный файлу при открытии с помощью оператора Open.

Функция EOF используется для предупреждения ошибок, вызываемых попытками выполнить чтение после конца файла. Она возвращает значение False, пока не будет достигнут конец файла.

Примеры чтения и записи в файл

Пример 1
Открытие (или создание, если он не существует) текстового файла для чтения и записи и запись в него одной строки, состоящей из двух текстовых и одного числового значений. Файл с именем myFile1.txt будет создан в той же папке, где расположен файл Excel с кодом VBA.

Sub Test1()

Dim ff As Integer

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем (или создаем) файл для чтения и записи

Open ThisWorkbook.Path & «myFile1.txt» For Output As ff

‘Записываем в файл одну строку

Write #ff, «Дает корова молоко!», _

«Куда идет король?», 25.35847

‘Закрываем файл

Close ff

‘Открываем файл для просмотра

ThisWorkbook.FollowHyperlink (ThisWorkbook.Path & «myFile1.txt»)

End Sub

Строки и число можно предварительно присвоить переменным, объявленным с соответствующими типами данных, и использовать их для записи данных в файл (в строках кода с оператором Write #, как в этом и следующем примерах).

Пример 2
Открытие (или создание, если он не существует) файла без расширения для чтения и записи и запись в него трех строк: двух текстовых и одной в числовом формате. Файл с именем myFile2 будет создан в той же папке, где расположен файл Excel с кодом VBA.

Так как у файла нет расширения, Windows выведет диалоговое окно для выбора открывающей его программы. Выберите любой текстовый редактор или интернет-браузер.

Sub Test2()

Dim ff As Integer

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем (или создаем) файл для чтения и записи

Open ThisWorkbook.Path & «myFile2» For Output As ff

‘Записываем в файл три строки

Write #ff, «Дает корова молоко!»

Write #ff, «Куда идет король?»

Write #ff, 25.35847

‘Закрываем файл

Close ff

‘Открываем файл для просмотра

ThisWorkbook.FollowHyperlink (ThisWorkbook.Path & «myFile2»)

End Sub

Пример 3
Считываем строку, разделенную на отдельные элементы, из файла myFile1.txt и записываем в три переменные, по типу данных соответствующие элементам.

Sub Test3()

Dim ff As Integer, str1 As String, _

str2 As String, num1 As Single

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile1.txt для чтения

Open ThisWorkbook.Path & «myFile1.txt» For Input As ff

‘Считываем строку из файла и записываем в переменные

Input #ff, str1, str2, num1

Close ff

‘Смотрим, что записалось в переменные

MsgBox «str1 = « & str1 & vbNewLine _

& «str2 = « & str2 & vbNewLine _

& «num1 = « & num1

End Sub

Попробуйте заменить в этом примере строку Input #ff, str1, str2, num1 сначала на строку Input #ff, str1, затем на строку Line Input #ff, str1, чтобы наглядно увидеть разницу между операторами Input # и Line Input #.

В следующих примерах (4 и 5) замена оператора Input # на Line Input # не приведет ни к каким изменениям, так как данные в строках файла myFile2 не разделены на элементы (поля).

Пример 4
Считываем поочередно три строки из файла myFile2 и записываем в три элемента массива, объявленного как Variant, так как в этот файл ранее были записаны две строки с текстом и одна с числом.

Sub Test4()

Dim ff As Integer, a(2) As Variant, i As Byte

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile2 для чтения

Open ThisWorkbook.Path & «myFile2» For Input As ff

‘Считываем строки из файла и записываем в элементы массива

   For i = 0 To 2

      Input #ff, a(i)

   Next

Close ff

‘Смотрим, что записалось в элементы массива

MsgBox «a(0) = « & a(0) & vbNewLine _

& «a(1) = « & a(1) & vbNewLine _

& «a(2) = « & a(2)

End Sub

Пример 5
Считываем с помощью цикла Do While… Loop все строки из файла myFile2 и записываем построчно в переменную, объявленную как String (число из третьей строки запишется как текст). Для остановки цикла при достижении конца файла используем функцию EOF.

Sub Test5()

Dim ff As Integer, a As Variant, b As String

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile2 для чтения

Open ThisWorkbook.Path & «myFile2» For Input As ff

‘Считываем строки из файла и записываем в элементы массива

   Do While Not EOF(ff)

      Input #ff, a

      b = b & a & vbNewLine

   Loop

Close ff

‘Смотрим, что записалось в переменную

MsgBox b

End Sub


Предыдущая часть темы об открытии файла для ввода и вывода информации опубликована в статье: Оператор Open (синтаксис, параметры). Смотрите также связанную статью: Функция FreeFile.

Смотрите, как создавать и открывать текстовые файлы с помощью методов CreateTextFile и OpenTextFile. Чтение файла, запись и добавление информации с помощью объекта TextStream.


Содержание

  1. Функция Input
  2. Синтаксис
  3. Возвращаемое значение
  4. Замечания
  5. Пример
  6. См. также
  7. Поддержка и обратная связь
  8. VBA Line Input Statement
  9. Line Input Description
  10. Line Input Syntax
  11. Examples of Excel VBA Line Input Statement
  12. VBA Coding Made Easy
  13. VBA Code Examples Add-in
  14. VBA Read Text Files
  15. Syntax to Read Text File
  16. VBA Read Text File Line by Line using Line Input Statement
  17. VBA Read Whole Data from Text File into String using Input Statement
  18. Instructions to Run VBA Macro Code or Procedure:
  19. Other Useful Resources:
  20. Line Input # statement
  21. Syntax
  22. Remarks
  23. Example
  24. See also
  25. Support and feedback
  26. VB & VBA in a Nutshell: The Language by Paul Lomax
  27. Syntax
  28. Description
  29. Rules at a Glance
  30. Example
  31. Programming Tips and Gotchas

Функция Input

Возвращает значение типа String (строка), содержащее знаки из файла, открытого в режиме Ввод или Двоичный.

Синтаксис

Input(number, [ # ]filenumber)

Синтаксис функции Input включает следующие элементы:

Part Описание
число Обязательный аргумент. Все допустимые числовые выражения, задающие количество возвращаемых символов.
filenumber Обязательно указывать. Любой допустимый номер файла.

Возвращаемое значение

Замечания

Данные, считанные с помощью функции Input , обычно записываются в файл с помощью Print # или Put. Эта функция используется только для файлов, открытых в режиме Ввод или Двоичный.

В отличие от инструкции Input # , функция Input возвращает все считываемые символы, включая запятые, возврат каретки, каналы строк, кавычки и пробелы в начале.

Если файлы открыты для двоичного доступа, попытка прочитать файл с помощью функции Input до тех пор, пока EOF не вернет значение True , создает ошибку. Используйте функции LOF и Loc вместо EOF при чтении двоичных файлов с помощью входных данных или get при использовании функции EOF .

Функция InputB используется для битовых данных, которые содержатся в текстовых файлах. С помощью функции InputB, элемент number задает число возвращаемый битов вместо количества возвращаемых символов.

Пример

В этом примере функция Input используется для чтения из файла отдельных символов и их печати в окно Интерпретация. В этом примере предполагается, что TESTFILE это текстовый файл с несколькими строками примеров данных.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Line Input Statement

In this Article

Line Input Description

Reads a single line from an Open sequential file and assigns it to a string.

Line Input Syntax

The Line Input statement contains 2 arguments:

FileNumber: Any valid file number.

VarName: Valid Varient or String variable name.

Examples of Excel VBA Line Input Statement

To test the Line Input Statement, create a text file “test.txt” on the D drive.(D:test.txt) Assume that the content of the file is as following.

Please run the following code.

Then, the result will be as following.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA Read Text Files

VBA Read Text Files using the Input Statement or the Line Input statement. The Input statement expects data that generates by Write and reads data into a list of variables. The Line Input statement reads the whole line of data as a single string variable. We can read text files either line by line or all lines. After Read Text files data and store into string, array, or Worksheet. Let us see different examples in the following tutorial.

Syntax to Read Text File

You can find following syntax to Read Data to Text File in Excel VBA.
Syntax:

Where FileNumber represents the unique number to file and contains numeric value. It helps to open text files.
Input_Value1, Input_Value2, … represents the input data which you want to write to text file. All values are separated by commas, and it adds hash marks(#) around dates and quotes(“) around strings while writing to text file.
and Line_Input_String represents the input string to write to text file.

VBA Read Text File Line by Line using Line Input Statement

You can find following VBA Code. It helps to Read all lines data from Text File Line by Line in Excel.

VBA Read Whole Data from Text File into String using Input Statement

You can find following VBA Code. Here we use Input statement to retrieve data. It helps to Read data from Text File into string variable in Excel. We are displaying output on the screen.

Output: You can find following Input and output screenshot for your reference.
VBA Read Text File into String Variable

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

Источник

Line Input # statement

Reads a single line from an open sequential file and assigns it to a String variable.

Syntax

Line Input #filenumber, varname

The Line Input # statement syntax has these parts:

Part Description
filenumber Required. Any valid file number.
varname Required. Valid Variant or String variable name.

Data read with Line Input # is usually written from a file with Print #.

The Line Input # statement reads from a file one character at a time until it encounters a carriage return (Chr(13)) or carriage return-linefeed (Chr(13) + Chr(10)) sequence. Carriage return-linefeed sequences are skipped rather than appended to the character string.

Example

This example uses the Line Input # statement to read a line from a sequential file and assign it to a variable. This example assumes that TESTFILE is a text file with a few lines of sample data.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VB & VBA in a Nutshell: The Language by Paul Lomax

Get full access to VB & VBA in a Nutshell: The Language and 60K+ other titles, with a free 10-day trial of O’Reilly.

There are also live events, courses curated by job role, and more.

Syntax

Data Type: Integer

Any valid file number.

Data Type: String or Variant

The name of a string or variant variable.

Description

Assigns a single line from a sequential file opened with the For Input method to a string or variant variable.

Rules at a Glance

Data is read into a buffer one character at a time until a line feed or carriage return sequence (either Chr(13) or Chr(13)+Chr(10)) is encountered. When this happens, all characters in the buffer are assigned to varname as a single string, without the carriage return sequence, and the buffer is cleared.

After reading a line, the file pointer advances to the first character after the end of the line or to the end-of-file marker.

Example

Programming Tips and Gotchas

You use the Line Input statement to read data from unstructured sequential data files. To write data back to this type of file, use the Print # statement.

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Источник

Return to VBA Code Examples

Line Input Description

Reads a single line from an Open sequential file and assigns it to a string.

Line Input Syntax

Line Input #FileNumber, VarName

The Line Input statement contains 2 arguments:

FileNumber: Any valid file number.

VarName: Valid Varient or String variable name.

Examples of Excel VBA Line Input Statement

To test the Line Input Statement, create a text file “test.txt” on the D drive.(D:test.txt) Assume that the content of the file is as following.

abc
1 2 3
xy z

Please run the following code.

Sub LineInput_Example()
    Dim strLine As String
    Dim strContent As String
    
    Open "D:test.txt" For Input As #1 ' Open file.
    Do While Not EOF(1) ' Loop until end of file.
        Line Input #1, strLine ' Read line into variable.
        strContent = strContent & strLine
    Loop
    Close #1 ' Close file.
    
    MsgBox strContent
End Sub

Then, the result will be as following.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Читает строку из открытого последовательного файла и присваивает ее переменной типа String.

Line Input #номерФайла, имяПеременной

Параметры
номерФайла
Обязательный. Любой допустимый номер файла.
имяПеременной
Обязательный. Допустимое имя переменной типа Variant или String.

Замечания
Данные, считываемые с помощью инструкции Line Input #, обычно записываются в файл с помощью инструкции Print #.
Инструкция Line Input # последовательно считывает из файла по одному символу до тех пор, пока не встретит символ возврата каретки (Chr(13)) или комбинацию символов возврата каретки и перевода строки (Chr(13) + Chr(10)). Когда считанная строка присваивается переменной, символы возврата каретки и конца строки отбрасываются.

Пример

В данном примере инструкция Line Input # используется для чтения строки из последовательного файла и присвоения ее переменной. Предположим, что текстовый файл TESTFILE существует и содержит несколько строк текста.

Dim TextLine
Open "TESTFILE" For Input As #1		' Открывает файл.
Do While Not EOF(1)			' Цикл до конца файла.
	Line Input #1, TextLine		' Читает строку в переменную.
	Debug.Print TextLine		' Выводит в окно "Отладка".
Loop
Close #1				' Закрывает файл.

VBA Read Text Files using the Input Statement or the Line Input statement. The Input statement expects data that generates by Write and reads data into a list of variables. The Line Input statement reads the whole line of data as a single string variable. We can read text files either line by line or all lines. After Read Text files data and store into string, array, or Worksheet. Let us see different examples in the following tutorial.

Table of Contents:

  • Objective
  • Syntax to Read Text File
  • VBA Read Text File Line by Line using Line Input Statement
  • VBA Read Whole Data from Text File into String using Input Statement
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Syntax to Read Text File

You can find following syntax to Read Data to Text File in Excel VBA.
Syntax:

Input #FileNumber, Input_Value1, Input_Value2, ...
'or
Line Input #FileNumber, Line_Input_String

Where FileNumber represents the unique number to file and contains numeric value. It helps to open text files.
Input_Value1, Input_Value2, … represents the input data which you want to write to text file. All values are separated by commas, and it adds hash marks(#) around dates and quotes(“) around strings while writing to text file.
and Line_Input_String represents the input string to write to text file.

VBA Read Text File Line by Line using Line Input Statement

You can find following VBA Code. It helps to Read all lines data from Text File Line by Line in Excel.

'VBA Read Text File Line by Line
Sub VBAF1_Read_Text_File_Line_by_Line()

    'Variable Declaration
    Dim sFilePath As String
    Dim strTextLine As String
    Dim iFile As Integer
    
    'Specify Text File Path
    sFilePath = "C:VBAF1FirstTextFile.txt"
    
    'Get Unique File Number using FreeFile
     fileNumber = FreeFile
    
    'Open Text File to Read Data
    Open sFilePath For Input As #fileNumber
    
    'Read Whole data in text file
    Do Until EOF(1)
        'Read data line by line
        Line Input #1, strTextLine
    Loop
    
    'Close Text File
    Close #fileNumber

End Sub

VBA Read Whole Data from Text File into String using Input Statement

You can find following VBA Code. Here we use Input statement to retrieve data. It helps to Read data from Text File into string variable in Excel. We are displaying output on the screen.

'VBA Read Text File into String Variable
Sub VBAF1_Read_Text_Into_String()

    'Variable Declaration
    Dim fileName As String, sVariableData As String, fileNumber As Integer
    
    'Specify Text File Path
    sFilePath = "C:VBAF1FirstTextFile.txt"
    
    'Get Unique File Number using FreeFile
     fileNumber = FreeFile
     
     'Open Text File to Read Data
    Open sFilePath For Input As #fileNumber
    
    'Store Data into a string variable
    sVariableData = Input$(LOF(fileNumber), #fileNumber)
    
    'Display output on the screen
    MsgBox sVariableData, vbInformation, "VBAF1"
    
    'Close Text File
    Close #fileNumber
    
End Sub

Output: You can find following Input and output screenshot for your reference.

VBA Read Text File into String Variable

VBA Read Text File into String Variable

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Понравилась статья? Поделить с друзьями:
  • Excel vba left описание
  • Excel vba for each range in range cells
  • Excel vba last column
  • Excel vba odbc connection
  • Excel vba for each next for