VB and VBA Users Source Code: Loading and saving data to text files
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Loading and saving data to text files
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, March 15, 2005
Hits:
3445
Category:
Files/Directories/IO
Article:
Below are two routines to load and save data to and from files, there is also an example routine at the bottom of this post. Option Explicit 'Purpose : Returns the contents of a text file. 'Inputs : sFileName The name of the file to load. 'Outputs : Returns the contents of the file, else returns an empty string. 'Author : Andrew Baker 'Date : 13/Jul/2001 'Notes : Function TextFileLoad(sFileName As String) As String Dim iFileNum As Integer, lFileLen As Long On Error GoTo ErrFailed 'Open File iFileNum = FreeFile 'Read file Open sFileName For Binary Access Read As #iFileNum lFileLen = LOF(iFileNum) 'Create output buffer TextFileLoad = String(lFileLen, " ") 'Read contents of file Get iFileNum, 1, TextFileLoad 'Close the file handle Close #iFileNum Exit Function ErrFailed: Debug.Print "Error in TextFileLoad: " & Err.Description Debug.Assert False 'Close the file handle Close #iFileNum 'File not found TextFileLoad = "" End Function 'Purpose : Save the specifed string to a text file (uses a shared file lock). 'Inputs : FileName The name of the file to save the text to. ' Text The text to save to the file. ' Append If true will append the text to any existing file, else will create a new file. 'Outputs : Returns true on success, else returns false. 'Author : Andrew Baker 'Date : 13/Jul/2001 'Notes : Function TextFileSave(FileName As String, Text As String, Append As Boolean) As Boolean Dim lFileNum As Integer On Error GoTo ErrFailed lFileNum = FreeFile 'Open the file using a shared lock '(enables multiple process to write to the file simultaneously) If Append Then Open FileName For Append Shared As #lFileNum Else Open FileName For Output Shared As #lFileNum End If 'Write to the file Print #lFileNum, Text 'Close the file handle Close #lFileNum TextFileSave = True Exit Function ErrFailed: 'Error Debug.Print "Error in TextFileSave: " & Err.Description Debug.Assert False If lFileNum Then 'Close the file handle Close #lFileNum End If 'Return failed TextFileSave = False End Function 'Demonstration routine Sub Test() Const TEST_FILE As String = "C:\Test.txt" Call TextFileSave(TEST_FILE, "Hello" & vbNewLine & "Andrew", False) Dim contents As String contents = TextFileLoad(TEST_FILE) Shell "Notepad " + TEST_FILE, vbNormalFocus End Sub
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder