Couple of ways of doing this. It is possible to check the read-only flag, but I usually try to delete the file first. If it fails to delete then you know that the file is either readonly, or is open in another application.
This code will check for existing file and read only status, hope this helps
Dim fso As FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("c:\temp\test.pdf") Then
If GetAttr("c:\temp\test.pdf") And vbReadOnly Then
'Save your file
You need to add Microsoft Scripting Runtime to references.
I have been looking for a way to check if the pdf I want to overwrite is open by a colleague. Mr. Pawar's code is working perfectly if you actually set the file to read only but for me this is not avoiding SW from becoming not responding if the old pdf file is open somewhere. Isn't there a way to check if the file, you want to overwrite, is open somewhere ?? Maybe to delete first is the only way to go!
use the following function, this checks whether the file is opened by another user.
Function IsFileOpen(FileName As String)
Dim f As Long
ErrNo As Long
On Error Resume Next
f = FreeFile()
Open FileName For Input Lock Read As #f
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsFileOpen = False
Case 70: IsFileOpen = True
Case Else: Error ErrNo
I know it's been a wile since there has been any activity on his thread but I came across it looking for the solution to an almost identical problem. Also since this thread is not marked as answered I thought I would direct you to this thread that I started and got working solution for. Thought it might work for you if you as well.