|
-
May 3rd, 2005, 03:34 PM
#1
Thread Starter
Addicted Member
VB-Excel SaveAs method, if file exists, rename without prompting
When using the SaveAs method in VB to save my Excel sheet, if the user entered an existing filename, I want my code to just append a 1 to the end of the filename, save it and move on, no prompting, etc.
Right now if the file exists, a msgbox pops up asking if i want to over-right, if you say no, it asks to save book1. I then want that saved as Filename-1 I want this to happen all behind the scenes.
I know I could probably do some FSO stuff to check but wondering if there is a shorter way, like does the SaveAs throw an error that I can trap?
Last edited by Kraig K; May 4th, 2005 at 02:31 PM.
-
May 3rd, 2005, 03:45 PM
#2
Re: VB-Excel SaveAs method, if file exists, rename without prompting
Personaly, I would use the FileExists API, then you will know ahead of time and prepare to save acordingly.
Also, once you have appened 1 to the FileName; that file too may exists. Therefore, you can iterate with a counter past the similar named files (using the API) until there is no match and append the counter (as the next sequential number).
Bruce.
-
May 3rd, 2005, 04:29 PM
#3
Re: VB-Excel SaveAs method, if file exists, rename without prompting
This will work for files with a number from 1 to 9.
VB Code:
If ActiveWorkbook.Saved = True Then
Dim sName As String
Dim i As Integer
Dim bNum As Boolean
sName = ActiveWorkbook.Name
'look for the version number
i = 1
Do While bNum = False
If IsNumeric(Mid$(ActiveWorkbook.Name, i, 1)) = True Then
bNum = True
Exit Do
End If
i = i + 1
Loop
If bNum = True Then
'Save and increment the number by 1
ActiveWorkbook.SaveAs Replace(ActiveWorkbook.Name, Mid$(ActiveWorkbook.Name, i, 1), Mid$(ActiveWorkbook.Name, i, 1) + 1)
Else
'Add a 1 to the end of the name
ActiveWorkbook.SaveAs Replace(ActiveWorkbook.FullName, ".xls", "1.xls")
End If
Else 'New book so save with name and 1.xls
ActiveWorkbook.SaveAs "C:\SomeFileName1.xls"
End If
VB/Office Guru™ (AKA: Gangsta Yoda™ ®)
I dont answer coding questions via PM. Please post a thread in the appropriate forum. 
Microsoft MVP 2006-2011
Office Development FAQ (C#, VB.NET, VB 6, VBA)
Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
If a post has helped you then Please Rate it! 
• Reps & Rating Posts • VS.NET on Vista • Multiple .NET Framework Versions • Office Primary Interop Assemblies • VB/Office Guru™ Word SpellChecker™.NET • VB/Office Guru™ Word SpellChecker™ VB6 • VB.NET Attributes Ex. • Outlook Global Address List • API Viewer utility • .NET API Viewer Utility •
System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6 
-
May 4th, 2005, 08:23 AM
#4
Thread Starter
Addicted Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
RobDog
Seems like the ActiveWorkbook.Saved property is always false for me. Here's what happens, the users starts a new data collection run, enters some information, then the filename is auto generated based on that info. Then the CommonDialog comes up asking where to save the file, my app defaults to the C:\Data folder, so this dialog allows users to change directories. The generated filename is in the SaveAs box already. Then the app acquires data, then attempts to save. At this point a new Excel workbook is created. Here's a summary of my creation of the Excel object.
VB Code:
'at top of code
Dim objExcel As New Excel.Application
Dim objBook As New Excel.Workbook
'then the savedata sub
With objExcel
Set objBook = .Workbooks.Add
'write some stuff
End With
'save the file
objBook.SaveAs FileName
'destroy objects
objExcel.Workbooks.Close
objExcel.Quit
Set objExcel = Nothing
So what I tried with your code is I put it where my SaveAs is and commented that out.
-
May 4th, 2005, 08:31 AM
#5
Re: VB-Excel SaveAs method, if file exists, rename without prompting
If you always want a completely unique filename, append the datetime to it. I do this with log files that get generated from my programs. My customers can run the program 20 times in a row and 20 unique files will be created. Something like
VB Code:
FileName = FileName & "_" & Format(Now, "mmddyyyyhhmmss") & ".xls"
-
May 4th, 2005, 08:51 AM
#6
Fanatic Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
If you append yyyymmddhhmmss instead of mmddyyyyhhmmss, then the user will be able to see (in Explorer), the list of files in chronological order.
-
May 4th, 2005, 08:55 AM
#7
Thread Starter
Addicted Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
That's an idea I didn't think of.
Thanks Hack and Rob.
If anyone has any other ideas, I'm listening...
-
May 4th, 2005, 09:06 AM
#8
Thread Starter
Addicted Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
Actually, just spoke to my coworker that I developed this for, appending all that to each filename may be a little much. I guess the chances of the same file are somewhat slim, the user SHOULD be changing the info that generates it but I wanted a failsafe in case they forget so they don't lose data.
So I guess I'm back to my original thought. Looks like if I say NO to over-right the existing file, I get a 1004 error. Hmmm, this may be a way to do the check...
-
May 4th, 2005, 09:18 AM
#9
Re: VB-Excel SaveAs method, if file exists, rename without prompting
 Originally Posted by Kraig K
Actually, just spoke to my coworker that I developed this for, appending all that to each filename may be a little much. I guess the chances of the same file are somewhat slim, the user SHOULD be changing the info that generates it but I wanted a failsafe in case they forget so they don't lose data.
Well, if the changes are slim, you could drop the time, and just append the date. FileName_05042005.xls shouldn't be that difficult to deal with.
-
May 4th, 2005, 09:34 AM
#10
Thread Starter
Addicted Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
I think I'd like to just append the 1 to it. Not that your suggestion isn't bad. Actually, just adding the date returns me to the original problem, how to determine if the file already exists. Some things I've discovered:
The ActiveWorkbook.Name doesn't get set to my desired filename until AFTER the SaveAs method.
SaveAs does throw error 1004 but before it does it asks if I want to over-right, turning DisplayAlerts off makes it select the default choise, which is yes.
Looking at the SaveAs help, it has a conflict resolution option, but the way it reads, it won't do what I want.
Sooo close.
-
May 4th, 2005, 02:30 PM
#11
Thread Starter
Addicted Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
Did some more searching and found some nice, simple code that does exactly what I want.
VB Code:
Dim fName As String
fName = "c:\test.xls"
If Len(Dir(fName, vbNormal)) = 0 Then
'Add code to create file
Else
'The file already exists, perform some operation
End If
Now I just need to make this robust to check the appended number and I'm good! Some of Robdog's code may help there.
Thanks all.
-
May 4th, 2005, 02:32 PM
#12
Re: VB-Excel SaveAs method, if file exists, rename without prompting
What was wrong with "If ActiveWorkbook.Saved = True Then"?
If the document has been saved then it exists.
If its not saved then its new and doesnt exist.
VB/Office Guru™ (AKA: Gangsta Yoda™ ®)
I dont answer coding questions via PM. Please post a thread in the appropriate forum. 
Microsoft MVP 2006-2011
Office Development FAQ (C#, VB.NET, VB 6, VBA)
Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
If a post has helped you then Please Rate it! 
• Reps & Rating Posts • VS.NET on Vista • Multiple .NET Framework Versions • Office Primary Interop Assemblies • VB/Office Guru™ Word SpellChecker™.NET • VB/Office Guru™ Word SpellChecker™ VB6 • VB.NET Attributes Ex. • Outlook Global Address List • API Viewer utility • .NET API Viewer Utility •
System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6 
-
May 4th, 2005, 02:45 PM
#13
Thread Starter
Addicted Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
 Originally Posted by RobDog888
What was wrong with "If ActiveWorkbook.Saved = True Then"?
If the document has been saved then it exists.
If its not saved then its new and doesnt exist.
I believe that the Saved property gets "reset" upon starting a new run in my app. Once the file is closed and the object is destroyed, the active workbook then became "Book1". In other words, once the file is closed, there is no more active workbook. Am I making sense?
-
May 4th, 2005, 03:01 PM
#14
Re: VB-Excel SaveAs method, if file exists, rename without prompting
Thats correct, but I guess I thought that there would be a saved version open in Excel at some point that would be used to test
against an existing file or instance.
VB/Office Guru™ (AKA: Gangsta Yoda™ ®)
I dont answer coding questions via PM. Please post a thread in the appropriate forum. 
Microsoft MVP 2006-2011
Office Development FAQ (C#, VB.NET, VB 6, VBA)
Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
If a post has helped you then Please Rate it! 
• Reps & Rating Posts • VS.NET on Vista • Multiple .NET Framework Versions • Office Primary Interop Assemblies • VB/Office Guru™ Word SpellChecker™.NET • VB/Office Guru™ Word SpellChecker™ VB6 • VB.NET Attributes Ex. • Outlook Global Address List • API Viewer utility • .NET API Viewer Utility •
System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6 
-
May 4th, 2005, 03:20 PM
#15
Thread Starter
Addicted Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
 Originally Posted by RobDog888
Thats correct, but I guess I thought that there would be a saved version open in Excel at some point that would be used to test against an existing file or instance.
I suppose it could if I didn't close the file after saving, but I like to.
Anyway, here's what I came up with to append a sequential number to the end and if that new filename also exists, go to the next number, etc.
VB Code:
Dim k As Integer
Dim fName As String
'check if file already exists
If Len(Dir(FileName, vbNormal)) = 0 Then 'file does not exist
objBook.SaveAs FileName
Else
fName = FileName
Do Until Len(Dir(FileName, vbNormal)) = 0
k = k + 1
FileName = Replace$(fName, ".xls", "-" & k & ".xls")
Loop
objBook.SaveAs FileName
End If
-
May 4th, 2005, 11:24 PM
#16
Fanatic Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
It would be nice, if the list of files (viewed in explorer) were chronological.
That can be achieved by padding in front with 0's
But that then raises the 'over adaption' of limiting you to say 001 to 999
I knocked this up.
It is a black box that allows you to pass any file name, and let it increment it for you.
You can optionally tell it what separator( _ ) to use, and what length you wish the incrementor to be ( 001 or 0001 or more)
VB Code:
Private Sub Form_Click()
Dim sFullFileName As String
Dim myStr As String
Dim cntr As Long
sFullFileName = "MyPicture.jpeg"
'sFullFileName = "MyPic.jpg"
myStr = sFullFileName
myStr = FileNameIncrement(myStr, "_") 'You could chg optional length from 3 to 4, by passing 4
Print myStr
For cntr = 0 To 11
myStr = FileNameIncrement(myStr, "_")
Print myStr
Next cntr
End Sub
'This pads the suffix(Incr), so that viewing of file names will be chronological.
'This will append say "_001"
'If you pass one with say "_003", then you'll get "_004" back
Public Function FileNameIncrement(sIN As String, Optional sSep As String = "_", Optional lenIncr As Long = 3) As String
'Author: Rob Crombie
Dim sFn As String ' MyPic
Dim sFnIncr As String ' 001 or 0001 or 00001
Dim sFnIncrMaybe As String
Dim lFnIncr As Long
Dim sFnExt As String ' .jpg or .jpeg
Dim sArr() As String
Dim sWork As String ' Working pad
Dim sWork2 As String ' Working pad
'Dim lLen As Long ' Usually 3 may be 4 (mutter, mutter)
Dim bVirgin As Boolean ' Lacks any previous incrementing
Dim sMsg As String
Dim sTitle As String
If InStr(sIN, ".") = 0 Then
sMsg = ""
sMsg = sMsg & " Please give full file name, including the extension" & vbCrLf
sMsg = sMsg & " An example would be MyPic.jpg"
sTitle = " YOU MUST ALSO INCLUDE THE FILE EXTENSION"
MsgBox sMsg, , sTitle
Exit Function '<== Exit Function
End If
sArr = Split(sIN, ".")
sWork = sArr(0) ' sWork contains everything to the left of the .
sFnExt = sArr(1) ' Contains say jpg
'Perhaps it hasn't been here before ?
If InStr(1, sWork, sSep) = 0 Then
'Definitely has never been appended
bVirgin = True
Else
'It contains sSep, but may just be part of file name ?
' sWork contains everything to the left of the .
sArr = Split(sWork, sSep)
sFnIncrMaybe = sArr(UBound(sArr))
If Len(sFnIncrMaybe) <> lenIncr Then
bVirgin = True
Else
'The sSep was in the correct place, but it may not be our sSep ?
' I'll assume that sSep & nnn is ours
If IsNumeric(sFnIncrMaybe) = True Then
'Lets convert it, and increment it, whilst we know what we are doing.
lFnIncr = CLng(sFnIncrMaybe) + 1
Else
bVirgin = True
End If
End If
End If
If bVirgin Then
'If it is a virgin, our job is easy. Just append say _001
FileNameIncrement = sWork & sSep & PadLeft("1", lenIncr, "0") & "." & sFnExt
Exit Function '<== Exit Function
Else
'It had a suffix like 006, so make that 007 instead
'sWork = MyPic_001 we want sFn = MyPic
sFn = Left(sWork, Len(sWork) - (lenIncr + 1))
'Convert the just incremented number to a string and pad it in front with 0
sWork2 = CStr(lFnIncr) '<== This may contain say 6, if it was _006
' Typically MyPic _ say 6 3 Pad chr
FileNameIncrement = sFn & sSep & PadLeft(sWork2, lenIncr, "0") & "." & sFnExt
End If
End Function
Public Function PadLeft(sIN As String, lngLen As Long, Optional sChar As String = " ") As String
'Author: Rob Crombie
Dim sPad As String
Dim i As Long
If Len(sIN) > lngLen Then
MsgBox "Passed string was too long. already", , "ERROR IN CODE THAT CALLED PadLeft"
Exit Function '<===== Exit Function
End If
'If "" was passed, then assume they meant " "
If Len(sChar) = 0 Then
sChar = " "
End If
For i = 1 To (lngLen - Len(sIN))
sPad = sPad & sChar
Next i
PadLeft = sPad & sIN
End Function
Last edited by RobCrombie; May 4th, 2005 at 11:59 PM.
Rob C
-
May 5th, 2005, 08:17 AM
#17
Thread Starter
Addicted Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
Cool Rob. A little more than what I need for the current project, but definitely looks useful! Maybe a batch file renamer??
I did change my code to append -01 so I can get up to 100 files in order, plenty for my current needs.
-
May 5th, 2005, 01:55 PM
#18
Fanatic Member
Re: VB-Excel SaveAs method, if file exists, rename without prompting
A little more than what I need for the current project
Ah, such is life
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|