Examples - Close Statement

Example 1:

For this first example:

  1. Create a text file named test.txt.

  2. Place it inside the d:\temp folder.

  3. Type some text into the file.

  4. Run the example script here:

Sub Main()
    Open "c:\test.txt" For Input As #1
    Do While Not EOF(1)
        MyStr = Input(10, #1)
        MsgBox MyStr
    Loop
    Close #1
End Sub

This script opens the file for reading, then loops through the text, 10 characters at a time. Each time it loops, it shows those ten characters in a message box. When it reaches the end of the file, it  closes the file.

Example 2:

This next example creates three text files, TestFile1.txt, TestFile2.txt, and TestFile3.txt in a D:\temp directory and writes some text into each file. It then closes those files:

Sub Main()
    Dim I, FNum, FName, PrevDir ' Declare variables.
    
    PrevDir = CurDir() ' Stores the current directory.
    ChDir "D:\temp\" ' Sets the current directory to this folder.
        For I = 1 To 3
            FNum = FreeFile ' Determines the next file number.
            FName = "TestFile" & FNum & ".txt" ' Defines the file name.
            MsgBox "Creating and writing to " & FName
            Open FName For Output As FNum ' Opens the file for writing.
            Print #I, "This is test #" & I ' Writes strings to the file.
            Print #I, "Here is another "; I
        Next I
    
    Close ' Closes all files.
    ChDir PrevDir ' Sets the directory back to what it was.
End Sub