Check before overwriting file?

F

Fan924

I am using the following to select a file name and then open file for
writing. It writes to the filename even if it is already used. Is
there a way to have it check before overwriting file? Examples?
________________________________

SaveFileName = Application.GetSaveAsFilename("C:\My Documents
\temp.hex", _
"Hex File (*.hex), *.hex", , "Save File As:")

Open SaveFileName For Output As #1
________________________________
 
C

Chip Pearson

Use something like

If Dir(SaveFileName) <> vbNullString Then
' file exists
Else
' file does not exist
End If

Cordially,
Chip Pearson
Microsoft MVP
Excel Product Group
Pearson Software Consulting, LLC
www.cpearson.com
(email on web site)
 
F

Fan924

Thanks Chip. I did a search using your example and found this. It
increments the file name until it finds a unique one. It was missing
an ELSE so it didn't work at first.


dim filename as string
dim try as long
try=1
another:
filename = "c:\test_" & try & ".txt"
if dir(filename)<>vbnullstring then 'the fiel exists! try another
try=try+1
goto another
msgbox("unused filename is " & filename)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top