These text file handling sessions are basically simple enough, but can get a little more complicated when specific logic is required - I'll get into that later.
First off, open Notepad or another light text editor and save a new file. I like to change the extension from .txt to something that is unique to my project - for instance .jus, or .anp, etc. The suffix can be anything; I like to change this from .txt so it is less likely that the file will be opened or its contents changed. Restructuring the contents may cause errors when it is loaded by the application. The .txt suffix can also be used as an alternative, however.
Private Sub Save_Click()
Open "C:\ArcNotepad.anp"
For Output As
#1
Print
#1, "1st line of the document"
Print
#1, "2nd line" 'Line 2, etc.
Close
#1
End Sub
Retrieve text from a file:
Private Sub Load_Click()
Dim strLine1
As Integer
Dim strLine2
As Integer
Open "C:\ArcNotepad.anp"
For Input As
#2
Line Input
#2, strLine1
Line Input
#2, strLine2 'etc.
Close
#2
End Sub
That's it for the basics, but let's insert some logic into this. The previous two examples will work if your formatting will be standard - that is, if the text file holds a set number of values/variables that will be updated over and over again, but the number of values will not change. An alternative situation is when lines are added or removed from the text document. The application will not know how many lines are included in the text file, and this is poses a problem. This dynamic text file requires some additional coding to be handled properly. The next time the document is accessed, there will be either:
- lines that are overlooked (more lines in the text file exist than the previous code looks to retrieve), or
- the program will return a "Run-time error '62': Input past end of file" error (there are too few lines available for the program to retrieve).
Private Sub Load_Click()
Dim i As Integer
Dim blank As String
'Count the number of lines in ArcNotepad.anp
Open "C:\ArcNotepad.anp" For Input As #2
Do While Not EOF(2)
Line Input #2, blank
i = i + 1
Loop Close #2
'Break: Show number of lines in ArcNotepad.anp
MsgBox "Lines: " & i
Dim ii As Integer
'Create a dynamic array, of size i
Dim strLine() As String
ReDim strLine(i)
'Populate the array with lines from ArcNotepad.anp
Open "C:\ArcNotepad.anp" For Input As #1
Do While Not EOF(1)
Line Input #1, strLine(ii)
ii = ii + 1
Loop Close #1
'Report the array via message box
Dim iii As Integer
Dim strMessage As String
For iii = 0 To i - 1
strMessage = strMessage & _
"Line " & iii + 1 & ": " & strLine(iii) & vbCrLf
Next iii
MsgBox strMessage
No comments:
Post a Comment