Write To File When Unloading Form
Can't a file be written in the Unload event of a Form? I am trying to populate a text file with some text in the Form's Unload event function:
Code:
Private Sub Form_Unload(Cancel As Integer)
Dim FileName As String
Dim iFile As Integer
If (Form2.chkLoad.Value = 0) Then
FileName = App.Path & "\MyFile.txt"
'the file is a hidden file; so changing it to a normal file for editing
SetAttr FileName, vbNormal
Open FileName For Output As #iFile
Write #iFile, "Windows"
Close #iFile
SetAttr FileName, vbHidden
End If
Unload Me
End Sub
But the above code generates the
Bad file name or number.
error pointing to the red line in the above code. I also tried the above code in the Form's QueryUnload event function but it generates the same error.
Is there any way to edit a file when the Form is unloaded?
Re: Write To File When Unloading Form
The problem is that iFile is zero. Add this
iFile = FreeFile
Re: Write To File When Unloading Form
BTW, by opening the file for Output you are going to overwrite it so why do SetAttr FileName, vbNormal?
Re: Write To File When Unloading Form
Oh and you don't need Unload Me in the Form_Unload event. You might want to consider however Set <yourforname> = Nothing because otherwise global variables in the form (if any) will maintain their values from the last time it was used.
Re: Write To File When Unloading Form
Quote:
The problem is that iFile is zero. Add this
iFile = FreeFile
Stupid.....indeed very stupid I am when I have written so many text files in this manner.
Quote:
BTW, by opening the file for Output you are going to overwrite it so why do SetAttr FileName, vbNormal?
Assuming that a file is hidden, shouldn't it be first be unhidden & then only can that file be written/overwritten?
Quote:
Oh and you don't need Unload Me in the Form_Unload event. You might want to consider however Set <yourforname> = Nothing because otherwise global variables in the form (if any) will maintain their values from the last time it was used.
Thanks for this useful tip
Re: Write To File When Unloading Form
Quote:
Originally Posted by arpan_de
....Assuming that a file is hidden, shouldn't it be first be unhidden & then only can that file be written/overwritten?
I'm not %100 sure, but try it.
Re: Write To File When Unloading Form
Yes....you have to unhide the hidden file first to edit it otherwise VB generates the Path/File access error error pointing to the red line in the code shown in thread #1.
Re: Write To File When Unloading Form
Okay, you (hopefully) learn something every day.
Re: Write To File When Unloading Form
Yup....that's very much true....all thanks to helpful friends like you (no pun intended)....