This is a repost--newsreader problems. But I did want to add that if you're
using xl2k or higher, you can remove the split97 function and just change this
line:
mySplit = Split97(FileNameToCheck, "\")
to
mySplit = Split(FileNameToCheck, "\")
(Split was added in xl2k.)
This is the original post:
How about something like this:
Option Explicit
Sub testme01()
Dim wkbk As Workbook
Dim myFileName As Variant
Set wkbk = ActiveWorkbook 'for testing
myFileName = Application.GetSaveAsFilename
If myFileName = False Then
Exit Sub 'user hit cancel
End If
If isFileNameInUse(wkbk, CStr(myFileName)) Then
MsgBox "there's a file with that name already open" _
& vbNewLine & "Try again"
Exit Sub
End If
Application.DisplayAlerts = False
wkbk.SaveAs Filename:=myFileName
Application.DisplayAlerts = True
End Sub
Function isFileNameInUse(wkbkToSave As Workbook, _
FileNameToCheck As String) As Boolean
Dim testWkbk As Workbook
Dim JustFileName As String
Dim mySplit As Variant
If StrComp(wkbkToSave.FullName, FileNameToCheck, vbTextCompare) = 0 Then
isFileNameInUse = False 'ok to SaveAs
Exit Function
End If
mySplit = Split97(FileNameToCheck, "\")
JustFileName = mySplit(UBound(mySplit))
Set testWkbk = Nothing
On Error Resume Next
Set testWkbk = Workbooks(JustFileName)
On Error GoTo 0
isFileNameInUse = Not CBool(testWkbk Is Nothing)
End Function
'from Tom Ogilvy
Function Split97(sStr As Variant, sdelim As String) As Variant
Split97 = Evaluate("{""" & _
Application.Substitute(sStr, sdelim, """,""") & """}")
End Function
It prompts the user for a name and then looks to see if you're just saving the
original file. If you are, then that seems like it's ok to me.
But if you're trying to duplicate a name of a file already open, then it stops
and yells.
Another way is just to turn off error checking and then check to see if an error
would have occurred:
On Error Resume Next
ActiveWorkbook.SaveAs Filename:="book1.xls", FileFormat:=xlNormal
If Err.Number <> 0 Then
MsgBox "something bad happened--save didn't occur"
Err.Clear
End If
On Error GoTo 0
(I had a different workbook named book1.xls already open.)