The following sample code reads the contents of a text file into a text box on a form.
- Start Notepad and create a new text document by typing a list of at least 10 words. Save the file as MyText.txt.
- Start Microsoft Access and open a new blank database.
- Create a new form not based on any table.
- Add a text box to the form. Set its Name property to MyText1. Size the text box so that it's large enough to fit the contents of the text file that it will contain.
- Add a command button to the form. Set the button's properties as
follows:
OnClick: =WriteFile()
Caption: Import Text
- Save the form as Form1.
- Create a new module and type the following line in the Declarations section if it is not already there:
Option Explicit
- Type or paste the following procedure:
Function WriteFile ()
' These variables store the text of the file.
Dim Linedata as String
Dim WholeFile as String
' Open the file. Replace "<pathname>" with the correct path
' to MyText.txt.
Open "C:\<pathname>\MyText.txt" For Input As #1
' Continue reading until end-of-file.
Do While Not EOF(1)
' Read a line of data.
Line Input #1, Linedata
' Store each line of data in the WholeFile variable.
WholeFile = WholeFile + Chr(13) & Chr(10) + Linedata
Loop
' Transfer contents of file to text box on form.
Forms!Form1![MyText1] = WholeFile
' Close the data file.
Close #1
End Function
- On the File menu, click Close and Return to Microsoft Access.
- Open Form1 in Form view and click the Import Text button.
Note that the contents of the MyText.txt file appear in the text box.
You can erase the contents of the text box by setting it to an empty variable, such as the following:
Forms!Form1![My_Text1] = Null
You can call this expression from the Immediate window or you can assign it to another button on the form.