Create new text documents using VBA

Often I'll need to write Excel data to text-format files. This includes, but is not limited to, files of the following types:

  • .txt
  • .csv
  • .1st
  • .asc
  • .php
  • .css
  • .diz
  • .err

And so on. In order to do so, I use a custom function that writes the contents of any String variable to a file on disk. All you need to do is populate the String variable and specify the folder and filename you want to create, and the function will create the file and output the String contents there.

The CreateFile Function

Function CreateFile(fileName As String, contents As String)
' creates file from string contents

Dim tempFile As String
Dim nextFileNum As Long

  nextFileNum = FreeFile

  tempFile = fileName

  Open tempFile For Output As #nextFileNum
  Print #nextFileNum, contents
  Close #nextFileNum

End Function

Sample usage

Dim myFile As String
  myFile = "Let's write this to a text file."

  CreateFile "C:\MyFile.txt", myFile

Note that this function does not include error handling, specifically, it does not check for the existence of the file before attempting to open and write to it. It will simply overwrite the existing file. To check for pre-existing files, use a function like FileFolderExists.

Example

Dim someText As String

someText = "Here is the text for the file I want to create."

If Not FileFolderExists("F:\Test\Readme.txt") Then
  CreateFile "F:\Test\Readme.txt", someText
End If

Site last updated: May 17, 2012

Peltier Tech Chart Utilities for ExcelPeltier Tech Waterfall Chart UtilityPeltier Tech Box and Whisker Chart UtilityPeltier Tech Cluster-Stack Chart UtilityPeltier Tech Panel Chart UtilityPeltier Tech Marimekko Chart UtilityPeltier Tech Dot Plot UtilityPeltier Tech Cascade Chart Utility