I am using the most recent version of SolidWorks 2015 Professional, and would like to check to see if a PDF file is read only. So far, I've tried three approaches with no success.
Approach #1: Catching the "Permission Denied" Error (Source)
Function IsFileOpen1(filename As String) As Boolean Dim filenum As Integer, errnum As Integer On Error Resume Next ' Turn error checking off. filenum = FreeFile() ' Get a free file number. ' Attempt to open the file and lock it. Open filename For Input Lock Read As #filenum Close filenum ' Close the file. errnum = Err ' Save the error number that occurred. On Error GoTo 0 ' Turn error checking back on. ' Check to see which error occurred. Select Case errnum ' No error occurred. ' File is NOT already open by another user. Case 0 IsFileOpen1 = False ' Error number for "Permission Denied." ' File is already opened by another user. Case 70 IsFileOpen1 = True ' Another error occurred. Case Else Error errnum End Select End Function
The problem with this is that the error is not captured. Specifically, I get the following error on line #07:
I don't understand why VBA isn't obeying the "On Error Resume Next" command.
Approach #2: Use the "GetAttr()" Command to Check if the File Is Read Only (Source)
Function IsFileOpen2(filename As String) As Boolean With CreateObject("Scripting.FileSystemObject") If .FileExists(filename) Then If GetAttr(filename) And vbReadOnly Then IsFileOpen2 = True Else IsFileOpen2 = False End If End With End Function
The problem here is that the GetAttr function always returns "32" (i.e. "vbArchive" or "File has been changed since last backup") whether the file is open or not. To be clear, at no point have I ever seen it be equal to "0" (i.e. "vbNormal" or "Normal") or "1" (i.e. "vbReadOnly" "Read-only").
Approach #3: Use Outputs from the "SaveAs" Command to Check if SolidWorks Was Successful in Saving the File (Source)
Dim exportData As SldWorks.ExportPdfData, status As Boolean, nErrors As Long, nWarnings As Long Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set exportData = swApp.GetExportFileData(swExportPdfData) exportData.ExportAs3D = True FilePath = Replace(swModel.GetPathName, ".sldprt", " (3D).pdf", 1, -1, vbTextCompare) status = swModel.Extension.SaveAs(FilePath, swSaveAsCurrentVersion, swSaveAsOptions_Silent, exportData, nErrors, nWarnings) If Not status Then MsgBox "PDF creation failed." End If
The problem is that whether the file is indeed read-only or not, the value returned to "status" is always "False", and the value of "nErrors" is always "swGenericSaveError".
Ultimately, if the file is not open, the PDF is saved successfully, but I want to be able to warn the user that the file failed to save, if that does happen.