This code will save a record to a sequential file; basically a clear text file where each record is separated by a return carriage (vbCrLf). This is useful for quick input / output scenarios where you don't want or need to use anything other than a text editor to review output or modify input. Note - using the Open For Append As statement means that if the file exists the code will open it and add the record to the end of the file. Otherwise the code will create the file and will add the record as the first entry.
Public Sub Save_To_Sequential()
'Set the path for the file
Save_Path = "C:\Temp\Test.txt"
'Assign the data you want to save to a variable
Data_To_Save = "This is a test line."
Open Save_Path for Append as #1
Print #1, Data_To_Save
Close #1
End Sub
Now to reverse the process, that is to read from a file a sequential file, you would use code like the following:
Public Sub Read_From_Sequential()
'Set the path for the file
Save_Path = "C:\Temp\Test.txt"
Open Save_Path for Input as #1
Line Input #1, Holder
'Holder is the variable to hold the record
Close #1
End Sub
Mind you these are simple examples that deal with single records only. To handle multiple records you just need to repeat the Print #1, Data_To_Save code while changing Data_To_Save to a new value to save each time (such as by using an array) when saving. When reading a file, each time you repeat the Line Input #1, Holder code, Holder will take on the value of the next line within the file.
For example, if you save a series of strings to a string array called Save_Items() and want to output them all to a file the following code would do just that.
Public Sub Multiple_Save_To_Sequential()
'Set the path for the file
Save_Path = "C:\Temp\Test.txt"
For I = 1 to ubound (Save_Items())
Open Save_Path for Input as #1
Print #1, Save_Items(I)
Close #1
Next I
End Sub
To read the file back into the array you would use the following:
Public Sub Multiple_Read_From_Sequential()
'Set the path for the file
Save_Path = "C:\Temp\Test.txt"
Open Save_Path for Input as #1
Do
Count = Count + 1
Redim Preserve Save_Items(Count)
Line Input #1, Holder
Save_Items(Count) = Holder
Loop While Seek(1) < LOF(1)
Close #1
End Sub
Keep in mind that the files created by this kind of code can be read and modified by anyone with a text editor such as note pad. This makes them great when you want to be able to make quick, easy changes to values on the fly, but less than desirable when you're dealing with data that confidential or sensitive.
No comments:
Post a Comment