For the following example, I have a user form called UserData. It has Three text boxes:
FirstName
LastName
Phone
In the form module global declarations area, I declared three variables to contain the text box values:
FName
LName
Ph
When the form loads, it reads in values from a text file. If the file doesn't exist, it is created and blank values are loaded in the textboxes.
When the user closes the form, a procedure writes the values to a txt file. If the user doesn't want to keep the values, blank lines are written to the text file. If the User closes from the Forms control icon, the confirmation message appears a second time.
Here's the code:
Option Compare Database
'Establish variables to track user choice of saving data
'*****Code by Thomas Lafferty*****
Dim FName
Dim Lname
Dim Ph
Private Sub Form_Close()
Call Close_UserData
End Sub
Private Sub Form_Load()
Open "C:\My Documents\UserData.txt" For Input As #1 ' Open file for input.
Do While Not EOF(1) ' Loop until end of file.
Input #1, FName, Lname, Ph ' Read data into variables.
FirstName.SetFocus
FirstName.Text = FName
LastName.SetFocus
LastName.Text = Lname
Phone.SetFocus
Phone.Text = Ph
Loop
Close #1 ' Close file.
End Sub
Private Sub Save_Close_Btn_Click()
Close_UserData
DoCmd.Close
End Sub
Public Function Close_UserData()
FirstName.SetFocus
FName = FirstName.Text
LastName.SetFocus
Lname = LastName.Text
Phone.SetFocus
Ph = Phone.Text
'*******variable to capture choice to save data******
Dim UserChoice
UserChoice = MsgBox("Do you want to save this data?", vbYesNo, "User Information")
If UserChoice = vbYes Then
Open "C:\My Documents\UserData.txt" For Output As #1
Print #1, FName
Print #1, Lname
Print #1, Ph
Close #1 'Close Output file
Else 'User chose no, so overwrite with blank lines
Open "C:\My Documents\UserData.txt" For Output As #1
Print #1,
Print #1,
Print #1,
Close #1 'Close Output file
End If
End Function