Создание текстового файла vba excel

Создание файлов Excel методами Workbooks.Add, Worksheet.Copy и текстовых файлов с помощью оператора Open и метода CreateTextFile из кода VBA Excel. Создание документов Word рассмотрено в отдельной статье.

Метод Workbooks.Add

Описание

Файлы Excel можно создавать из кода VBA с помощью метода Add объекта Workbooks.

Workbooks.Add – это метод, который создает и возвращает новую книгу Excel. Новая книга после создания становится активной.

Ссылку на новую книгу Excel, созданную методом Workbooks.Add, можно присвоить объектной переменной с помощью оператора Set или обращаться к ней, как к активной книге: ActiveWorkbook.

Синтаксис

Workbooks.Add (Template)

Template – параметр, который определяет, как создается новая книга.

Значение Template Параметры новой книги
Отсутствует Новая книга с количеством листов по умолчанию.
Полное имя существующего файла Excel Новая книга с указанным файлом в качестве шаблона.
xlWBATChart Новый файл с одним листом диаграммы.
xlWBATWorksheet Новый файл с одним рабочим листом.

Примеры

Пример 1
Создание новой книги Excel с количеством листов по умолчанию и сохранение ее в папку, где расположен файл с кодом VBA:

Sub Primer1()

‘Создаем новую книгу

Workbooks.Add

‘Сохраняем книгу в папку, где расположен файл с кодом

ActiveWorkbook.SaveAs (ThisWorkbook.Path & «Моя новая книга.xlsx»)

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

ActiveWorkbook.Close

End Sub

Файл «Моя новая книга.xlsx» понадобится для следующего примера.

Пример 2
Создание новой книги по файлу «Моя новая книга.xlsx» в качестве шаблона с присвоением ссылки на нее объектной переменной, сохранение нового файла с новым именем и добавление в него нового рабочего листа:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub Primer2()

‘Объявляем объектную переменную с ранней привязкой

Dim MyWorkbook As Workbook

‘Создаем новую книгу по шаблону файла «Моя новая книга.xlsx»

Set MyWorkbook = Workbooks.Add(ThisWorkbook.Path & «Моя новая книга.xlsx»)

    With MyWorkbook

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

        MsgBox .Name ‘»Моя новая книга1″

        ‘Сохраняем книгу с новым именем

        .SaveAs (ThisWorkbook.Path & «Моя самая новая книга.xlsx»)

        ‘Смотрим новое имя файла

        MsgBox .Name ‘»Моя самая новая книга»

        ‘Добавляем в книгу новый лист с именем «Мой новый лист»

        .Sheets.Add.Name = «Мой новый лист»

        ‘Сохраняем файл

        .Save

    End With

End Sub

Метод Worksheet.Copy

Описание

Если в коде VBA Excel применить метод Worksheet.Copy без указания параметра Before или After, будет создана новая книга с копируемым листом (листами). Новая книга станет активной.

Примеры

Пример 3
Создание новой книги с помощью копирования одного листа (в этом примере используется книга, созданная в первом примере):

Sub Primer3()

‘Если книга источник не открыта, ее нужно открыть

Workbooks.Open (ThisWorkbook.Path & «Моя новая книга.xlsx»)

‘Создаем новую книгу копированием одного листа

Workbooks(«Моя новая книга.xlsx»).Worksheets(«Лист1»).Copy

‘Сохраняем новую книгу с именем «Еще одна книжица.xlsx» в папку,

‘где расположен файл с кодом

ActiveWorkbook.SaveAs (ThisWorkbook.Path & «Еще одна книжица.xlsx»)

End Sub

Также, как и при создании нового файла Excel методом Workbooks.Add, при создании новой книги методом Worksheet.Copy, можно ссылку на нее присвоить объектной переменной.

Пример 4
Создание новой книги, в которую включены копии всех рабочих листов из файла с кодом VBA:

Sub Primer4()

ThisWorkbook.Worksheets.Copy

End Sub

Пример 5
Создание новой книги, в которую включены копии выбранных рабочих листов из файла с кодом VBA:

Sub Primer5()

ThisWorkbook.Sheets(Array(«Лист1», «Лист3», «Лист7»)).Copy

End Sub

Создание текстовых файлов

Оператор Open

При попытке открыть несуществующий текстовый файл с помощью оператора Open, такой файл будет создан. Новый файл будет создан при открытии его в любом режиме последовательного доступа, кроме Input (только для чтения).

Пример

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Sub Primer6()

Dim ff As Integer, ws As Object

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

ff = FreeFile

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

‘несуществующего в режиме чтения и записи

Open ThisWorkbook.Path & «Мой-новый-файл.txt» For Output As ff

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

Write #ff, «Этот файл создан при его открытии оператором « & _

«Open по несуществующему адресу (полному имени).»

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

Close ff

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

Set ws = CreateObject(«WScript.Shell»)

ws.Run ThisWorkbook.Path & «Мой-новый-файл.txt»

Set ws = Nothing

End Sub

В имени текстового файла пробелы заменены дефисами (знаками минус), так как метод Run объекта Wscript.Shell не способен открывать файлы с именами, содержащими пробелы.

Рекомендую открывать файлы для просмотра методом ThisWorkbook.FollowHyperlink. Пример и преимущества этого метода в статье VBA Excel. Открыть файл другой программы.

Метод FileSystemObject.CreateTextFile

Для создания нового текстового файла из кода VBA Excel по указанному имени, можно использовать метод CreateTextFile объекта FileSystemObject.

Пример

Sub Primer7()

Dim fso, fl, ws

‘Создаем новый экземпляр объекта FileSystemObject

Set fso = CreateObject(«Scripting.FileSystemObject»)

‘Присваиваем переменной fl новый объект TextStream,

‘связанный с созданным и открытым для записи файлом

Set fl = fso.CreateTextFile(ThisWorkbook.Path & «Еще-один-текстовый-файл.txt»)

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

fl.Write («Этот текстовый файл создан методом CreateTextFile объекта FileSystemObject.»)

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

fl.Close

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

Set ws = CreateObject(«WScript.Shell»)

ws.Run ThisWorkbook.Path & «Еще-один-текстовый-файл.txt»

End Sub

Стоит отметить, что новый текстовый файл может быть создан и с помощью метода OpenTextFile объекта FileSystemObject при условии присвоения параметру create значения True.

I have a file which is manually added or modified based on the inputs. Since most of the contents are repetitive in that file, only the hex values are changing, I want to make it a tool generated file.

I want to write the c codes which are going to be printed in that .txt file.

What is the command to create a .txt file using VBA, and how do I write to it

ashleedawg's user avatar

ashleedawg

20k8 gold badges73 silver badges104 bronze badges

asked Jul 16, 2012 at 11:20

danny's user avatar

2

To elaborate on Ben’s answer:

If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.

Here is a complete example module:

Option Explicit

' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()

    Dim filePath As String
    filePath = "C:tempMyTestFile.txt"

    ' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
    ' (Intellisense) work, which helps you avoid typos and lets you discover other useful
    ' methods of the FileSystemObject
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    ' Here the actual file is created and opened for write access
    Set fileStream = fso.CreateTextFile(filePath)

    ' Write something to the file
    fileStream.WriteLine "something"

    ' Close it, so it is not locked anymore
    fileStream.Close

    ' Here is another great method of the FileSystemObject that checks if a file exists
    If fso.FileExists(filePath) Then
        MsgBox "Yay! The file was created! :D"
    End If

    ' Explicitly setting objects to Nothing should not be necessary in most cases, but if
    ' you're writing macros for Microsoft Access, you may want to uncomment the following
    ' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
    'Set fileStream = Nothing
    'Set fso = Nothing

End Sub

answered Apr 5, 2018 at 14:16

Marcus Mangelsdorf's user avatar

3

an easy way with out much redundancy.

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim Fileout As Object
    Set Fileout = fso.CreateTextFile("C:your_pathvba.txt", True, True)
    Fileout.Write "your string goes here"
    Fileout.Close

answered Feb 23, 2016 at 17:01

pelos's user avatar

pelospelos

1,6743 gold badges24 silver badges32 bronze badges

2

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")

    Console.WriteLine("")

    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:A-Level Computing2017!PPESaveFileSaveData.txt", "Text: " & SaveVar & ", ", True)

    Console.WriteLine("")

    Console.WriteLine("File Saved")

    Console.WriteLine("")

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:A-Level Computing2017!PPESaveFileSaveData.txt"))
    Console.ReadLine()

End Sub()

BDL's user avatar

BDL

20.7k19 gold badges52 silver badges52 bronze badges

answered Feb 10, 2017 at 13:16

Zack Brightman's user avatar

5

Return to VBA Code Examples

This tutorial will demonstrate how to create a text file with VBA.

Create a Text File

This lesson uses the FileSystemObject. In order to use it, you will need to set a reference to the VB script run-time library.

To create a text file, you can use this code below with CreateTextFile Method.

Sub FSOCreateTextFile()
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Dim TextFile As Object

    Set TextFile = FSO.CreateTextFile("C:TestTestFile.txt")

End Sub

You can pass optional arguments to the CreateTextFile method:

  • If you set the “overwrite” argument to true, an already existing file can also be overwritten.
  • Setting the “unicode” argument true, a unicode file is created, otherwise (or if the argument is omitted) the result will be an ASCII file.

In the following example, an existing TestFile.txt will be overwritten with a unicode file:

Set TextFile = FSO.CreateTextFile("C:TestTestFile.txt", True, True)

Writing to Text File

After creating a text file you can write text to the file using a single line of code:

TextFile.Write "content"

Click the link to learn more about writing to text files using Write, WriteLine, WriteBlankLines methods.

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!

Home / VBA / VBA Create and Write to a Text File

To create a text using a VBA code, you need to use the CreateTextFile method. This method allows you to define a location where you want to create it. This method has a syntax that where you can specify if you want to overwrite the file on the location and specify whether the file is created as a Unicode or ASCII file.

Use the following steps:

  1. First, you need to use a FileSystemObject or Folder object to use with the method.
    1-create-a-text-fie-using-vba
  2. After that, you need to create another object use the CreateTextFile method.
    2-create-text-file-method
  3. In this code, we have used the TRUE to overwrite if there’s already a file with the same name in the folder.
  4. In the end, when you run this macro, create a new text file in the folder, just like the following.
Sub create_text_file()

'object to use as folder
Dim fld As Object
Set fld = CreateObject("Scripting.FileSystemObject")

'using create text file method
Dim myFile As Object
Set myFile = fld.CreateTextFile("C:UsersDellDesktopmyFoldermyTextFile.txt", True)
 
End Sub

Syntax for CreateTextFile Method

CreateTextFile (filename, [ overwrite, [ unicode ]])
  • filename: Path and the name of the file that you want to create.
  • overwrite: Boolean to define if you want to overwrite the file (if already exists) (optional).
  • unicode: Boolean to define whether the file is created as a Unicode or ASCII file (optional).

Write to a Text File using VBA

There are two statements that you can use to write data to a text file:

  1. Write: With this statement, you can write data to a text file where you will have commas between values, quotes around strings, and # signs around dates.
    3-write-statement
  2. Print: With this statement, you can write data to a text file with the exact appearance that you in the Excel worksheet.
    4-print-statement

Now ahead we will look at examples for both statements and understand how to write a complete code to write to a text file. But before that, you need to understand some of the terminologies to write the code the way you want.

  • For Output: You can use this command when you want to write data or want to modify data into a text file.
  • For Input: With this command, you can extract data from a text, but you won’t be able to modify and add data to the file.
  • For Append: This command helps you to add new data to the bottom of the text file.
  • FreeFile: You can use it to define a file number that is not in use to the text file that you want to use so that you would be able to refer to it.

Now let’s write a code to enter data into a text file.

  1. First, you need to declare variables to use in the code.
    5-declare-variables
  2. After that, you need to define the range that you need to write to the text file. And use the count of the cells of the range as a counter for the loop by defining it to a variable.
    6-define-the-range
  3. Next, you need to define the address of the text file where you want to add data.
    7-define-the-address-of-the-text-file
  4. From here, you need to declare the “FreeFile” command to a variable to get the file number.
    8-freefile-command
  5. Now, you need to create use the “Output” command as you need to add data to the file.
    9-output-command
  6. Finally, you need to use the “For Next” loop to get values from range one by one and add it to the file.
    10-for-next-loop-to-get-values
  7. Also, you need to use the close command to close the text file once data has been added to it.
    11-close-command
  8. In the end, when you run this macro, it adds data from the range A1:A13 to the text file that you have saved at the path you have mentioned.
    12-run-the-macro

Note: Make sure to change the path of the text file from the code according to the path you have in your system.

Option Explicit
Sub data_to_text_file()

'variables that you need to use in the code
Dim TextFile As Integer
Dim iCol As Integer
Dim myRange As Range
Dim cVal As Range
Dim i As Integer
Dim myFile As String

'define the range that you want to write
Set myRange = Range("A1:A13")
iCol = myRange.Count

'path to the text file (MAKE SURE TO CHANGE IT)
myFile = "C:UsersDellDesktopNewFoldertextfile.txt"

'define FreeFile to the variable file number
TextFile = FreeFile

'using append command to add text to the end of the file
Open myFile For Output As TextFile

'loop to add data to the text file
For i = 1 To iCol
Print #TextFile, Cells(i, 1),
Print #TextFile, Cells(i, 2)
Next i

'close command to close the text file after adding data
Close #TextFile

End Sub

I have a file which is manually added or modified based on the inputs. Since most of the contents are repetitive in that file, only the hex values are changing, I want to make it a tool generated file.

I want to write the c codes which are going to be printed in that .txt file.

What is the command to create a .txt file using VBA, and how do I write to it

ashleedawg's user avatar

ashleedawg

20k8 gold badges73 silver badges104 bronze badges

asked Jul 16, 2012 at 11:20

danny's user avatar

2

To elaborate on Ben’s answer:

If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.

Here is a complete example module:

Option Explicit

' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()

    Dim filePath As String
    filePath = "C:tempMyTestFile.txt"

    ' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
    ' (Intellisense) work, which helps you avoid typos and lets you discover other useful
    ' methods of the FileSystemObject
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    ' Here the actual file is created and opened for write access
    Set fileStream = fso.CreateTextFile(filePath)

    ' Write something to the file
    fileStream.WriteLine "something"

    ' Close it, so it is not locked anymore
    fileStream.Close

    ' Here is another great method of the FileSystemObject that checks if a file exists
    If fso.FileExists(filePath) Then
        MsgBox "Yay! The file was created! :D"
    End If

    ' Explicitly setting objects to Nothing should not be necessary in most cases, but if
    ' you're writing macros for Microsoft Access, you may want to uncomment the following
    ' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
    'Set fileStream = Nothing
    'Set fso = Nothing

End Sub

answered Apr 5, 2018 at 14:16

Marcus Mangelsdorf's user avatar

3

an easy way with out much redundancy.

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim Fileout As Object
    Set Fileout = fso.CreateTextFile("C:your_pathvba.txt", True, True)
    Fileout.Write "your string goes here"
    Fileout.Close

answered Feb 23, 2016 at 17:01

pelos's user avatar

pelospelos

1,6743 gold badges24 silver badges32 bronze badges

2

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")

    Console.WriteLine("")

    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:A-Level Computing2017!PPESaveFileSaveData.txt", "Text: " & SaveVar & ", ", True)

    Console.WriteLine("")

    Console.WriteLine("File Saved")

    Console.WriteLine("")

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:A-Level Computing2017!PPESaveFileSaveData.txt"))
    Console.ReadLine()

End Sub()

BDL's user avatar

BDL

20.7k19 gold badges52 silver badges52 bronze badges

answered Feb 10, 2017 at 13:16

Zack Brightman's user avatar

5

Понравилась статья? Поделить с друзьями:
  • Создание теста в excel скачать
  • Создание текстового поля word
  • Создание таблицы на андроиде excel
  • Создание текстового материала в документах word
  • Создание теста в excel макрос