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

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
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,223,911
Messages
6,175,325
Members
452,635
Latest member
laura12345

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