Had some time to waste (well, not really, but I like to keep my vba skills sharp). Here is a scenario that figures out if the file exists and asks the user what to do about it. You should be able to modify the code to suit your control names and folder path. The function was written to go into the form module since I don't see the rest of the db needing it. If you want to expose the check for a control being null or empty string, suggest you put a function in a standard module, pass the control to it and return a boolean of true or false. You'd call it from this or any other code that needs it. This is one of the few times I'd use a GoTo to control execution; it makes more sense than to repeat code to close or destroy variables in several places. You might want to embellish the error handler in the sub.
P.S. I think this works with the basic project references, but if I'm wrong you will get an error.
Code:
Private Sub Command15_Click()
Dim fs, f
Dim fPath As String, strMsg As String, strTxt As String
Dim result As Integer
Const ForReading = 1, ForWriting = 2, ForAppending = 8
On Error GoTo errHandler
If IsNull(Me.Text11) Or Me.Text11 = "" Then
MsgBox "Please enter information to be written to file."
Exit Sub
End If
strTxt = Me.Text11
fPath = "C:\Users\blahblah...\Notepad_" & Format(Date, "ddmmyyyy") & ".txt"
Set fs = CreateObject("Scripting.FileSystemObject")
If FileExists(fPath) Then
strMsg = "File exists; " & vbCrLf & "click Yes to overwrite, No to append or Cancel"
result = MsgBox(strMsg, vbYesNoCancel, "OVER-WRITE FILE?")
If result = vbCancel Then GoTo exitHere
If result = vbYes Then Set f = fs.OpenTextFile(fPath, 2) 'over-write
If result = vbNo Then
Set f = fs.OpenTextFile(fPath, 8) 'append
strTxt = vbCrLf & strTxt 'insert line feed/carriage return before string
End If
Else
Set f = fs.CreateTextFile(fPath, 2)
End If
f.write strTxt
Application.FollowHyperlink fPath 'opens the file to display success/failure.
exitHere:
On Error Resume Next
f.Close
Set fs = Nothing
Set f = Nothing
Exit Sub
errHandler:
MsgBox "Error " & Err.Number & ": " & Err.Description
Resume exitHere
End Sub
Code:
Function FileExists(fPath As String) As Boolean
Dim fs, f
On Error GoTo errHandler
FileExists = True
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile(fPath, 8)
'Close f
Set f = Nothing
Set fs = Nothing
Exit Function
errHandler:
'more than 1 err.number can result if file doesn't exist, so just use >0
If Err.Number > 0 Then FileExists = False 'file does not exist
Err.Clear
End Function