The following macro uses the OpenFileNameDialog function to open a File Open dialog box and request a file, and then tries to write to that file. If the file is read-only, the error handler (using the Err object) displays a "Path/File access error" with an error code of 75, and returns the user to the File Open dialog box. The line continuation character, an underscore preceded by a space, is used to break up long lines of code.
Private Type OPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
lpstrFile As String
nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
Flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
Declare Function GetOpenFilename _
Lib "COMDLG32.DLL" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
Function OpenFileNameDialog() As String
Dim fileName As String
Dim OFN As OPENFILENAME
With OFN
'Size of structure.
.lStructSize = Len(OFN)
'Size of buffer.
.nMaxFile = 260
'Create buffer.
.lpstrFile = String(.nMaxFile - 1, 0)
'Call function.
Ret = GetOpenFilename(OFN)
'Non-zero is success.
If Ret <> 0 Then
'Find first null char.
n = InStr(.lpstrFile, vbNullChar)
'Return what's before it.
fileName = Mid(.lpstrFile, 1, n - 1)
OpenFileNameDialog = .lpstrFile
End If
End With
End Function
Sub WriteToFile()
Dim fileName As String
On Error GoTo MyHandler
chooseAgain:
fileName = OpenFileNameDialog()
Open fileName For Append As #1
Write #1, "stuff"
Close #1
Exit Sub
MyHandler:
'If the file is read-only, let the user try again.
'The underscore character is used here to break the long line.
If Err.Number = 75 Then
MsgBox "Can't write to file" & fileName & _
". Please choose another.", , "File Error"
Resume chooseAgain
'For other errors display the error message, close the
'open file and exit.
Else
MsgBox Err.Number & ": " & Err.Description, , "File Error"
Close #1
Exit Sub
End If
End Sub
Note: If you have existing Reflection Basic error-handling code that was written without using the Err object, you can use it in Visual Basic without rewriting it. (The default property of the Err object is Number.) Because the default property can be represented by the object name Err, earlier code written using the Err function or Err statement doesn't have to be modified.