Excel vba for append as

Главная » Функции VBA »

28 Апрель 2011              99026 просмотров

  • CurDir() — функция, которая возвращает путь к каталогу(для указанного диска), в котором по умолчанию будут сохраняться файлы:
        Dim sCurDir As String
        sCurDir = CurDir("D")
  • Dir() — позволяет искать файл или каталог по указанному пути на диске. Пример использования можно посмотреть в статье: Просмотреть все файлы в папке
  • EOF() — при операции записи в файл на диске эта функция вернет True, если вы находитесь в конце файла. Обычно используется при работе с текстовыми файлами — .txt. При сохранении книг Excel лучше использовать стандартные методы: Save и SaveAs.
  • Error() — позволяет вернуть описание ошибки по ее номеру. Генерировать ошибку нужно при помощи метода RaiseError() специального объекта Er.
  • Print — записывает в открытый файл указанный текст. Далее будет приведен пример использования данной функции
  • FreeFile() — позволяет определить номер следующего свободного файла, который можно использовать как номер файла при его открытии методом Open. Предпочтительно применять именно этот метод определения номера файла(вместо статичного #1), чтобы не было неоднозначности обращения к файлам. Ниже приведены примеры применения данной функции при обращении к файлам
  • FileAttr() — позволяет определить, как именно был открыт файл в файловой системе: на чтение, запись, добавление, в двоичном или текстовом режиме и т.п. Применяется для работы с текстовыми файлами, открытыми при помощи Open "C:Text1.txt" For [] As #1
    Открыть файл можно несколькими способами, приведу примеры наиболее распространенных вариантов:

    • Input() — открывает текстовый файл на чтение. Т.е. таким методом можно открыть файл и вытянуть из него данные. Например, чтобы считать информацию из файла C:Text1.txt и вывести ее в окно Immediate можно применить такой код:
          Dim MyChar
          Open "C:Text1.txt" For Input As #1 'Открываем файл функцией Open() на чтение(Input)
          Do While Not EOF(1)  'пока файл не кончился
              ' Получаем по одному символу и добавляем его к предыдущим
              MyChar = MyChar & Input(1, #1)
          Loop
          Close #1 ' Закрываем файл
          'Выводим его содержание в окно Immediate
          '(отобразить Immediate: Ctrl+G в окне редактора VBA)
          Debug.Print MyChar
          'или в MsgBox
          MsgBox MyChar, vbInformation, "www.excel-vba.ru"
    • Ouput() — метод открывает файл для записи. Например, чтобы записать в файл строку, содержащую все ячейки в выделенном диапазоне, можно использовать такой код:
      Sub SelectionToTxt()
          Dim s As String, rc As Range
          Dim ff
          'запоминаем все значения из выделенной строки в строку
          For Each rc In Selection
              If s = "" Then 'если пока ничего не записали - присваиваем только значение ячейки
                  s = rc.Value
              Else 'если уже записано - добавляем через TAB
                  s = s & vbTab & rc.Value
              End If
          Next
          ff = FreeFile
          'Открываем текстовый файл
          'если файла нет - он будет создан
          Open "C:Text1.txt" For Output As #ff
          'записываем значение строки в файл
          Print #ff, s
          Close #ff ' Закрываем файл
      End Sub

      Важно помнить, что при открытии файла таким методом(Output) все предыдущие данные из файла стираются и в файле будет записано только то, что мы записали в текущем сеансе. Если данные необходимо добавить к имеющимся — используется метод Append

    • Append() — метод открывает файл для записи, но в отличии от Output записывает данные в конец файла, а не перезаписывает текущие данные. Например, код добавления выделенных ячеек как одной строки в имеющийся файл будет выглядеть так:
      Sub SelectionToTxt_Add()
          Dim s As String, rc As Range
          Dim ff
          'запоминаем все значения из выделенной строки в строку
          For Each rc In Selection
              If s = "" Then 'если пока ничего не записали - присваиваем только значение ячейки
                  s = rc.Value
              Else 'если уже записано - добавляем через TAB
                  s = s & vbTab & rc.Value
              End If
          Next
          ff = FreeFile
          'Открываем текстовый файл
          'если файла нет - он будет создан
          Open "C:Text1.txt" For Append As #ff
          'записываем значение строки в файл
          Print #ff, s
          Close #ff ' Закрываем файл
      End Sub
  • FileDateTime() — позволяет получить информацию о последнем времени обращения к указанному файлу. Если к файлу после создания ни разу не обращались, то это будет время создания файла. Если попытаться обратиться к уже открытой книге/файлу — то будет получено время открытия книги/файла, а не создания или сохранения.
        sFileDateTime = FileDateTime("C:Text1.txt")
  • FileLen() — позволяет определить длину указанного файла в байтах:
        MsgBox FileLen("C:Text1.txt") & " bites", vbInformation, "www.excel-vba.ru"
  • GetAttr() — возможность обратиться к файлу к файловой системе и получить информацию об его атрибутах (скрытый, доступен только для чтения, архивный и т.п.)
  • InputB() — позволяет указывать количество байт, которые надо считать из файла. Альтернатива методу Open в случаях, когда необходимо считывать данные не по конкретным строкам, а именно побайтово.
  • Loc() — от Location, то есть местонахождение — возвращает число, которое определяет текущее место вставки или чтения в открытом файле.
  • Seek() — очень похожа на функцию Loc(), но Seek() возвращает информацию о позиции, с которой будет выполняться следующая операция чтения или вставки.
  • LOF() — length of file — позволяет определить длину открытого файла в байтах.

Статья помогла? Сделай твит, поделись ссылкой с друзьями!

VBA Create Delete Modify Text Files

Automating Text Files With VBA Useful?

Text files can be a very fast and simple way to read and store information. I like to use them to save settings for my VBA add-ins or credentials for my macros that need to log into something.

I have seen situations where databases have exported large amounts of data into .txt files instead of Excel files (especially back in the days with Excel 2003).

Below are the main techniques I use to create, modify, extract data, and delete text files.

VBA Commands For Text File

When you are working with text files, there will be some terms used that you probably haven’t seen or used before when writing VBA code.  Let’s walk through these commands as you will see them throughout the VBA macros in this guide.

  • For Output — When you are opening the text file with this command, you are wanting to create or modify the text file. You will not be able to pull anything from the text file while opening with this mode.

  • For Input — When you are opening the text file with this command, you are wanting to extract information from the text file. You will not be able to modify the text file while opening it with this mode.

  • For Append — Add new text to the bottom of your text file content.

  • FreeFile — Is used to supply a file number that is not already in use. This is similar to referencing Workbook(1) vs. Workbook(2). By using FreeFile, the function will automatically return the next available reference number for your text file. 

  • Write — This writes a line of text to the file surrounding it with quotations

  • Print — This writes a line of text to the file without quotes

Create/Save A Text File With VBA Code

In this section, you will learn how to generate a new Text file and write data into it.

The Open function in combination with the For Output command creates a new text file automatically if the provided file path yields no result. The For Output command lets you enter an editing state instead of a read-only state.

After the new text file has been opened, you can utilize the Print function to write data to the text file. Each Print command adds a new line to the file.

Once you are finished writing data into the text file, you can simply Close it to save your changes.

Sub TextFile_Create()
‘PURPOSE: Create A New Text File
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String

‘What is the file path and name for the new text file?
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file
  Open FilePath For Output As TextFile

‘Write some lines of text
  Print #TextFile, «Hello Everyone!»
  Print #TextFile, «I created this file with VBA.»
  Print #TextFile, «Goodbye»

  ‘Save & Close Text File
  Close TextFile

End Sub

Create Text File From Spreadsheet Data

If you would like to write data into a new Text file from your spreadsheet, you can tweak the prior VBA macro code to loop through a range of cells and Print the cell data to the file.

Here’s an example of what you could create:

Sub TextFile_Create()
‘PURPOSE: Create A New Text File And Write Spreadsheet Data to File
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim cell As Range

‘What is the file path and name for the new text file?
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file
  Open FilePath For Output As TextFile

‘Write Spreadsheet Data To File (exclude blank cells)
  For Each cell In Range(«A1:A20»)
    If cell.Value <> «» Then Print #TextFile, cell.Value
  Next cell

  ‘Save & Close Text File
  Close TextFile

End Sub

Extracting All Data From A Text File With VBA Code

If you are just wanting to pull the entirety of a text file’s contents and work with it in your VBA code, you can simply dump all the data into a string variable and then proceed to work with it.

The below VBA macro code will open a specific text file and store all of its contents into a string-based variable called FileContent. It’s then up to you to decide what you want to do next with that information :)

Sub TextFile_PullData()
‘PURPOSE: Send All Data From Text File To A String Variable
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

‘File Path of Text File
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file
  Open FilePath For Input As TextFile

‘Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

‘Report Out Text File Contents
  MsgBox FileContent

‘Close Text File
  Close TextFile

End Sub

Edit/Modify A Text File With VBA Code (With Find/Replace)

If you need to edit the contents of a text file, you can open the file up in the For Input state. This will allow you to change things around and save your modifications.

For the example code in this article, you’ll learn how to use a Find and Replace functionality to replace all instances of the word “Goodbye” with “Cheers”.

We will also talk about adding data to the very end of a text file in a later section of this article.

Sub TextFile_FindReplace()
‘PURPOSE: Modify Contents of a text file using Find/Replace
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

‘File Path of Text File
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file in a Read State
  Open FilePath For Input As TextFile

‘Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

‘Clost Text File
  Close TextFile

  ‘Find/Replace
  FileContent = Replace(FileContent, «Goodbye», «Cheers»)

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file in a Write State
  Open FilePath For Output As TextFile

  ‘Write New Text data to file
  Print #TextFile, FileContent

‘Close Text File
  Close TextFile

End Sub

Append Data To Your Text File With VBA Code

If you need to add data to the end of an existing text file, you can perform an Append action to the file.

The following VBA macro code shows you how to:

  1. Open a text file

  2. Write 3 lines of new data to the very bottom

  3. Save and close the file

Sub TextFile_Create()
‘PURPOSE: Add More Text To The End Of A Text File
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String

‘What is the file path and name for the new text file?
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file
  Open FilePath For Append As TextFile

‘Write some lines of text
  Print #TextFile, «Sincerely,»
  Print #TextFile, «»
  Print #TextFile, «Chris»

  ‘Save & Close Text File
  Close TextFile

End Sub

Deleting A Text File Macro Code

If you would like to automate deleting a text file, you can utilize the Kill command.

Delete A Single Text File With VBA

The following VBA macro code deletes a specific text file from the user’s Desktop.

Sub TextFile_Delete()
‘PURPOSE: Delete a Text File from your computer
‘SOURCE: www.TheSpreadsheetGuru.com

Dim FilePath As String

‘File Path of Text File
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Delete File
  Kill FilePath

End Sub

Delete All Text Files In A Folder

If you are looking to perform file deletions on a larger scale you can write a looping macro that deletes all .txt files within a specified folder.

Sub DeleteTextFilesInFolder()
‘PURPOSE: To loop through and delete all Text files in a folder
‘SOURCE: www.TheSpreadsheetGuru.com

Dim FolderPath As String
Dim TextFile As String
Dim FileExtension As String
Dim Counter As Long

‘Determine Folder Path and File Extension Type
  FolderPath = «C:UserschrisDesktop»
  FileExtension = «*.txt»

‘Target Path with Ending Extention
  TextFile = Dir(FolderPath & FileExtension)

‘Loop through each Excel file in folder
  Do While TextFile <> «»
    Kill FolderPath & TextFile ‘Delete file
    TextFile = Dir ‘Get next file name
    Counter = Counter + 1
  Loop

‘Message Box when tasks are completed
  MsgBox «Text Files Delete: » & Counter

End Sub

VBA To Read A Text File Line By Line

This section will show you how to extract each line or row of data from your text file. This may be helpful if you need to pass the data through some sort of logic test or if you are searching for certain data points within the text file.

Write Each Text File Line To The Spreadsheet

The following VBA macro code reads through each line of a designated text file and writes the entire line to a cell in your spreadsheet (you determine the starting point with the variable StartCell).

Sub AddTextFileToSpreadsheet()
‘PURPOSE: Loop through each row in Text File & Write to Excel
‘SOURCE: www.TheSpreadsheetGuru.com

Dim FilePath As String
Dim TxtLine As String
Dim StartCell As Range
Dim x As Long

‘Text File Path
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine first cell you want data in
  Set StartCell = ActiveSheet.Range(«A1»)

‘Open the text file in a Read State
  Open FilePath For Input As FreeFile

  ‘Loop through each row in Text File and Write to Spreadsheet
  Do Until EOF(1)
    Line Input #1, TxtLine
    StartCell.Offset(x) = TxtLine
    x = x + 1
  Loop

    ‘Close Text File
  Close FreeFile

  End Sub

Write Each Text File Line To An Array Variable

The following VBA macro code reads through each line of a designated text file and writes the entire line to an array variable name LineArray. You can reference any line by writing the row number you are targeting and subtracting 1 (since array values start at 0 instead of 1).

For example, to retrieve the data stored in Row 5 you would write LineArray(5-1) or simply LineArray(4).

Sub TextFileLinesToArray()
‘PURPOSE: Load an Array variable with each line of data text file
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
Dim LineArray() As String

‘Text File Path
  FilePath = «C:UserschrisDesktopMyFile.txt»

  ‘Open the text file in a Read State
  TextFile = FreeFile
  Open FilePath For Input As TextFile

  ‘Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

‘Close Text File
  Close TextFile

  ‘Separate Out lines of data (vbCrLf = Page Break)
  LineArray() = Split(FileContent, vbCrLf)

  ‘Communicate How Many Lines are in Text File
  MsgBox «There were » & UBound(LineArray) + 1 & » lines of data found in the Text File»

End Sub

Fill Array With Delimited Text File Data With VBA Code

This VBA macro code can read a Text file from a provided path and populate an array variable by splitting the data based on a delimiter (separator).

The Delimiter variable is what determines how to split the data. In the below example a semi-colon is being used. The most common delimiter in text files is a comma character.

Sub DelimitedTextFileToArray()
‘PURPOSE: Load an Array variable with data from a delimited text file
‘SOURCE: www.TheSpreadsheetGuru.com

Dim Delimiter As String
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
Dim LineArray() As String
Dim DataArray() As String
Dim TempArray() As String
Dim rw As Long, col As Long

‘Inputs
  Delimiter = «;»
  FilePath = «C:UserschrisDesktopMyFile.txt»
  rw = 0

  ‘Open the text file in a Read State
  TextFile = FreeFile
  Open FilePath For Input As TextFile

  ‘Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

‘Close Text File
  Close TextFile

  ‘Separate Out lines of data
  LineArray() = Split(FileContent, vbCrLf)

‘Read Data into an Array Variable
  For x = LBound(LineArray) To UBound(LineArray)
    If Len(Trim(LineArray(x))) <> 0 Then
      ‘Split up line of text by delimiter
        TempArray = Split(LineArray(x), Delimiter)

            ‘Determine how many columns are needed
        col = UBound(TempArray)

            ‘Re-Adjust Array boundaries
        ReDim Preserve DataArray(col, rw)

            ‘Load line of data into Array variable
        For y = LBound(TempArray) To UBound(TempArray)
          DataArray(y, rw) = TempArray(y)
        Next y
    End If

        ‘Next line
      rw = rw + 1

      Next x

End Sub

I Hope This Microsoft Excel Article Helped!

Hopefully, I was able to explain how you can use VBA macro coding to manipulate and interact with Text Files for automated solutions. If you have any questions about this technique or suggestions on how to improve it, please let me know in the comments section below.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon! — Chris

Skip to content

VBA append to existing text file Excel Macros Examples Codes

Home » VBA » VBA append to existing text file Excel Macros Examples Codes

  • vba append to existing text file

VBA code to VBA append to existing text file Excel Macros Examples for writing to text files using VBA in MS Office Word, PowerPoint, Access, Excel 2003, 2007, 2010, 2013 and VBScript. This Example VBA Program and function will help you to know how to append a text file using Excel VBA.

vba append to existing text file

Appending an existing text file Using VBA

Here is the Procedure, Example VBA Syntax and Example VBA Macro code for Appending an existing text file in Excel VBA. This will help you to know how to append a text file and add data using VBA.

VBA append to existing text file: Procedure

We will first open the text file as Append file with a file number. Then we will add the data to the file using File Number.

VBA append a text file: Syntax

Here is the VBA code and syntax for Appending an existing text file Using VBA. Use the Append keyword to open text file in appending mode.

strFile_Path = "Your file Path"
Open strFile_Path For Append As #1
Write #1, “You can write your required text here”

VBA to Append existing text file: Example Macro Code

Following is the sample Excel Macro to write to a text file by appending it using Excel VBA.

Sub VBA_to_append_existing_text_file()
    Dim strFile_Path As String
    strFile_Path = "C:temptest.txt" ‘Change as per your test folder and exiting file path to append it.
    Open strFile_Path For Append As #1
    Write #1, "This is my sample text"
    Close #1
End Sub 

Instructions to run the VBA Macro code to append a text file

Please follow the below steps to execute the VBA Code to Append an existing text file using Excel VBA Editor.

Step 1: Open any Excel workbook

[ To Open MS Excel: Go to Start menu, All programs and select Excel from MS Office OR You can simply type excel in the run command (Press Windows+ r key to open run dialog)]
Step 2: Press Alt+F11 to open the VBA Editor [You can also open the VBE from the Developer Tab in the Excel ribbon]
Step 3: Insert a code module [Go to insert menu in the VBE and then press Module OR Simply press the Alt+i then m to insert code module]
Step 4: Copy the above Example Macro code and paste in the code module which have inserted in the above step
Step 5: Change the folder path as per your testing folder structure and existing file path.
Step 6: Now press the F5 to Run and Execute the Macro.
You can press the F8 to debug the macro line by line and see the result immediately.

Once you are done with the macro execution, now you can observe that a text file in the test folder. And the text file in the folder is appended with the data which you have mentioned in the code.

VBA Code to Append an existing text file – Macro Explained

Here is the detailed explanation of the Excel macro to append a text file using VBA.

  • Starting the program and sub procedure to write VBA Code to Append an existing text file and adding the data.
  • Declaring the strFile_Path variable as String Data Type to store the text file path.
  • Assigning the Existing File path to the variable strFile_Path.
  • Opening the text file for Append with FileNumber as 1.
  • Writing to the sample text to the File using FileNumber and Write Command.
  • Closing the File using FileNumber.
  • Ending the Sub procedure to write VBA Code to Append an existing text file and updating the data.

Here is the commented macro code for writing to text file and append it using VBA.

‘Starting the program and sub procedure to write VBA code to write the data to a text file Append.
Sub VBA_to_append_existing_text_file()

‘Declaring the strFile_Path variable as String Data Type to store the text file path.
Dim strFile_Path As String

‘Assigning the Existing File path to the variable strFile_Path.
strFile_Path = “C:temptest.txt”

‘Opening the text file for Append with FileNumber as 1.
Open strFile_Path For Append As #1

‘Writing to the sample text to the File using FileNumber and Write Command.
Write #1, “This is my sample text”

‘Closing the File using FileNumber.
Close #1

End Sub
‘Ending the Sub procedure to write VBA Code to append the data in existing text file.

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • Appending an existing text file Using VBA
    • VBA append to existing text file: Procedure
    • VBA append a text file: Syntax
    • VBA to Append existing text file: Example Macro Code
      • Instructions to run the VBA Macro code to append a text file
    • VBA Code to Append an existing text file – Macro Explained

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

4 Comments

  1. Eric
    June 18, 2015 at 3:14 PM — Reply

    Does anyone have a solution of how to capture the content on a cell (say a1) instead of “This is my sample text”?

  2. Eric
    June 18, 2015 at 8:24 PM — Reply

    No worries….worked it out….Range(“A!”)….
    Thanks for forum. Great code

  3. Rick
    February 23, 2016 at 3:12 AM — Reply

    I am getting the string in quotes i.e “my text here” . How do I remove that so that I just have ‘my text here’ in the text file?

  4. Jeremy
    May 19, 2016 at 3:23 PM — Reply

    You need to use “Print” instead of “Write”

    i.e. Instead of
    strFile_Path = “Your file Path”
    Open strFile_Path For Append As #1
    Write #1, “You can write your required text here”

    Use
    strFile_Path = “Your file Path”
    Open strFile_Path For Append As #1
    Print #1, “You can write your required text here”

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

VBA Append to Text File using two statements. It is almost same like Write date to text files. There is only one difference between Writing and appending data to text files. Just need to replace in Write or Print statement with append instead of Input or mode mode. The first statement is Write or the second statement is Print. The Write statement generates a line of values and it is separated by commas, and adds hash marks(#) around dates and quotes(“) around strings. The Print statement generates a line which is suitable to be printed, with the data is arranged in columns with spaces between. Let us learn syntax and examples on Write and print statements.

Table of Contents:

  • Objective
  • Syntax for Append to Text File
  • Appending data to Text File using Write Statement
  • Appending data to Text File using Print Statement
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Syntax for Append to Text File

You can find following syntax for Append to Text File in Excel VBA.
Syntax:

Write #FileNumber, Input_Value1, Input_Value2, ...
'or
Print #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 Append to Text File. All values are separated by commas, and it adds hash marks(#) around dates and quotes(“) around strings while Appending to text file.
and Line_Input_String represents the input string to Append to Text File.

Appending to Text File using Write Statement

You can find following VBA Code. It helps to Append to Text Files using Write statement in Excel.

'Appending data to Text File using Write Statement
Sub VBAF1_Append_Text_File_Using_Write_Statement()
    
    'Variable Declaration
    Dim sFilePath As String
    Dim iStRow As Integer, iLstRow As Integer
    Dim dDate As Date, sCountry As String, sRegion As String, iUnits As Integer
   
   'Specify Text File Path
    sFilePath = "C:VBAF1FirstTextFile.txt"
        
    'Get Unique File Number using FreeFile
    fileNumber = FreeFile
    
    'Check Specified Text File exists or not
    If VBA.Dir(sFilePath) = "" Then MsgBox "File Does not exists": End
    
    'Open TextFile in Append mode
    Open sFilePath For append As #fileNumber
    
    'Find Last Row
    iLstRow = Sheets("Input Data").Cells.SpecialCells(xlCellTypeLastCell).Row
        
    'Loop through all rows in Worksheet
    For iStRow = 2 To iLstRow
        'Append Data to Text File
        With Sheets("Input Data")
            dDate = .Cells(iStRow, 1).Value
            sCountry = .Cells(iStRow, 2).Value
            sRegion = .Cells(iStRow, 3).Value
            iUnits = .Cells(iStRow, 4).Value
        End With
    
        'Write Data to Text File
        Write #fileNumber, dDate, sCountry, sRegion, iUnits
       
    Next
    
    'Close Text File
    Close #fileNumber
        
End Sub

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

VBA Append Text Files in Notepad

VBA Append Text Files in Notepad

Appending to Text File using Print Statement

You can find following VBA macro. It helps to Append to Text Files using Print statement in Excel.

'Appending data to Text File using Print Statement
Sub VBAF1_Append_Text_File_Using_Print_Statement()
    
    'Variable Declaration
    Dim sFilePath As String
    Dim iStRow As Integer, iLstRow As Integer
    Dim sDataLine As String
   
   'Specify Text File Path
    sFilePath = "C:VBAF1FirstTextFile.txt"
        
    'Get Unique File Number using FreeFile
    fileNumber = FreeFile
    
    'Check Specified Text File exists or not
    If VBA.Dir(sFilePath) = "" Then MsgBox "File Does not exists": End
    
    'Open TextFile in Append mode
    Open sFilePath For append As #fileNumber
    
    'Find Last Row
    iLstRow = Sheets("Input Data").Cells.SpecialCells(xlCellTypeLastCell).Row
        
    'Loop through all rows in Worksheet
    For iStRow = 2 To iLstRow
        'Append Data to Existing Text File
        With Sheets("Input Data")
            sDataLine = Format(.Cells(iStRow, 1).Value, "dd-mmm-yyyy") & ";"
            sDataLine = sDataLine & .Cells(iStRow, 2).Value & ";"
            sDataLine = sDataLine & .Cells(iStRow, 3).Value & ";"
            sDataLine = sDataLine & .Cells(iStRow, 4).Value
        End With
    
        'Write Data to Text File
        Print #fileNumber, sDataLine
       
    Next
    
    'Close Text File
    Close #fileNumber
        
End Sub

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

Группа: Пользователи

Ранг: Новичок

Сообщений: 37


Репутация:

1

±

Замечаний:
0% ±


Excel 2010

Здравствуйте!

Необходимо написать код, который будет бегать по листу Excel’я, данные записывать в текстовый файл, и сохранять текстовый файл в туже директорию, где лежит файл с макросом.
Написал вот такой код:
[vba]

Код

    Set objFSO = CreateObject(«Scripting.FileSystemObject»)
    v = ThisWorkbook.Path
    Set objFile = objFSO.CreateTextFile(v & ActiveSheet.Name & «.txt»)
    For i = 2 To Sheets(«sec»).UsedRange.Rows.Count
      For j = 4 To Sheets(«sec»).UsedRange.Columns.Count
        If Sheets(«sec»).Cells(i, j).Value <> «» Then
          objFile.writeline (Sheets(«sec»).Cells(i, j).Value)
        End If
      Next j
    Next i
  MsgBox («Созданный файл сохранен: » & ThisWorkbook.Path)

[/vba]

Однако, файл не сохраняется. Причем я вижу, что директория в ThisWorkbook.Path отображается верно. Вариант с ActiveWorkbook.Path тоже пробовал, не помогло.
Подскажите пожалуйста, в чем может быть проблема!

Like this post? Please share to your friends:
  • Excel vba for all selected cells
  • Excel vba for all open workbooks
  • Excel vba fonts color
  • Excel vba font not bold
  • Excel vba font color in cell