Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write to external text file

How To

Write to external text file

by  randysmid  Posted    (Edited  )
Here is a bit of code that you can use to write things to an external text file. (I've included some optional code to delete the external text file too) This code will only write one line to the text file, but if you want multiple lines, simply put the "write" statement inside a loop.

dim strList as String
'loop through calculations here
' assign the values, e.g., "A", "B", etc. to strList
' example: strList = strList & strNewValue
Open "c:\List.txt" For Output As #1
Write #1, strList
Close #1


NOTE: with the example above, you may want to keep track of the number of characters contained within strList, so that your line doesn't exceed the width of your printer. In that case, you can use the "len" function as follows:
If len(strList) > 70 Then
Write #1, strList
strList = ""
End If


The following example creates a custom filename using the current date, and then opens the output file.
Dim strFileName As String
'it is necessary to use "DatePart" because "Date"
' would return a value that includes slash marks,
' which is interpreted by VB/VBA to be a folder name
strFileName = "c:\TEST" & DatePart("m", Date) & DatePart("dd", Date) & DatePart("yyyy", Date) & ".txt"
Open strFileName For Output As #1


It isn't so straightforward to delete files in Access. It will be necessary to declare a FileSystemObject. Here is the code:
Dim fso As Object, fsoFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set fsoFile = fso.GetFile("c:\TEST" & DatePart("m", Date) & DatePart ("dd", Date) & DatePart("yyyy", Date) & ".txt")
fsoFile.Delete


Feedback, comments?
Randy Smith, MCP
rsmith@cta.org [pc2]



Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top