Save excel file adding a number to file name

Osmario

New Member
Joined
Aug 28, 2016
Messages
4
Hi

I need a VBA code to save an excel file by addind a number to the end of file name.
For example Myfile.xlsm must be save as Myfile1.xlsm or Myfile2.xlsm or Myfile3.xlsm
and so on.

Best regards
Osmario
 

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
Try this. It saves in the active workbook's folder, but you can change this to a specific folder if necessary.
Code:
Public Sub Test()
    Dim fileName As String
    fileName = GetNextFileName(ActiveWorkbook.Path & "\MyFile|n|.xlsm")
    MsgBox "Next file name is " & fileName
    ActiveWorkbook.SaveCopyAs fileName  'or SaveAs
End Sub

Public Function GetNextFileName(filePath As String) As String

    Dim n As Integer
    
    n = 0
    Do
        n = n + 1
        GetNextFileName = Replace(filePath, "|n|", n)  
    Loop Until Dir(GetNextFileName) = vbNullString
    
End Function<n><n>
</n></n>
 
Last edited:
Upvote 0
Another possible option
Code:
Sub SaveAsNextNumber()
  Dim oldName As String, newName As String, sExt As String
  Dim i As Long
  
  oldName = ActiveWorkbook.FullName
  sExt = "." & Split(oldName, ".")(UBound(Split(oldName, ".")))
  oldName = Left(oldName, Len(oldName) - Len(sExt))
  i = Len(oldName)
  If Right(oldName, 1) Like "#" Then
    Do While Mid(oldName, i - 1, 1) Like "#"
      i = i - 1
    Loop
    newName = Left(oldName, i - 1) & Mid(oldName, i) + 1 & sExt
  Else
    newName = oldName & 1 & sExt
  End If
  ActiveWorkbook.SaveAs Filename:=newName
End Sub
 
Upvote 0

Forum statistics

Threads
1,216,522
Messages
6,131,146
Members
449,626
Latest member
Stormythebandit

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top