: Check if the file exists before you write to it. Place your code in this order:
:
:
: Private Sub cmdFile_Click()
: Dim Error
: Dim i As Integer
: Dim FileExists as Boolean
: cmdATP_Click
: If Dir(FileName) <> vbNullString Then
: FileExists = True
: Error = MsgBox("This File Already Exists, Over Write?", vbYesNo, "File Error")
: End If
:
: If Error = vbYes OR Not FileExists then
: Open FileName For Output Access Write As #1
: Print #1, ReportText
: Close #1
: End if
: End Sub
:
:
:
:
:
: : In my program, the user can click a command button to save information which is being displayed in a text box. The file name is also provided by the user in another text box called FileName. I want to be able to detect the file and if it exists, a message box will pop up asking the user if they want to overwrite the existing file or cancel. I can get the file detected but it still saves. Any ideas?
: :
: : Private Sub cmdFile_Click()
: : Dim Error
: : Dim i As Integer
: : cmdATP_Click
: : Open FileName For Output Access Write As #1
: : Print #1, ReportText
: : Close #1
: :
: : If Dir(FileName) <> vbNullString Then
: : Error = MsgBox("This File Already Exists, Over Write?", vbYesNo, "File Error")
: : End If
: :
: : End Sub
: :
: :
: :
:
:
Here's my version:
Private Sub cmdFile_Click()
If Dir$(FileNameBox.Text) = "" Then If MsgBox("File exists. Overwrite?", vbYesNo) = vbNo Then Exit Sub
Open FileNameBox.Text For Output As 1
Print #1, TextToSave.Text
Close 1
End Sub
To use the commondialog control:
Ctrl+T
-or-
Right-click toolbox, click Components
-or-
(Menu) Project - Components
Place a check next to Microsoft Common Dialog Control. Click OK.
Place a copy of new control on your form.
CommonDialog1.ShowOpen
FileName = CommonDialog1.FileName
Look it up in the help for, it has a lot of uses, including ShowSave, Printer, Fonts, Colors. Also look at CancelError (error raised when cancel is clicked) so you can know when the user cancels. FileTitle, Filters, FilterIndex will also be helpful.
Hope this helps!