MrExcelicius
MrExcelicius

Reputation: 13

Excel VBA to remove formulas and save as v2

In the following code, I am trying to adjust so I loop through all the files on a tab, and if the range has formulas to convert it to value. But only for the specific tab. Before closing and saving the file, I want to save it as the current name and add in the end " _v2". Can someone help on that?

    Sub LoopAllExcelFilesInFold2()
    'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

    Dim wb As Workbook
    Dim myPath As String
    Dim myFile As String
    Dim myExtension As String
    Dim FldrPicker As FileDialog
    Dim rng As Range
    'Optimize Macro Speed
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
   .Title = "Select A Target Folder"
   .AllowMultiSelect = False
   If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With

'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"

'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)

'Ensure Workbook has opened before moving on to next line of code
DoEvents
On Error Resume Next

Sheets("Cubes Act'20").Select
For Each rng In ActiveSheet.UsedRange
If rng.HasFormula Then
rng.Formula = rng.Value
End If
Next rng








'Save and Close Workbook
'wb.Close SaveChanges:=True
wb.Close ActiveWorkbook.SaveCopyAs("filename" & "_v2")

'Ensure Workbook has closed before moving on to next line of code
DoEvents

'Get next file name
myFile = Dir
Loop

'Message Box when tasks are completed
MsgBox "Task Complete!"

ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

Upvotes: 1

Views: 325

Answers (1)

Tony Dallimore
Tony Dallimore

Reputation: 12413

I believe the function NextFileName() does what you want.

I almost always have version numbers on my files, so I regularly need to find new name “AAA V28.xxx” when I have finished updating file “AAA V27.xxx”. I keep function NextFileName() in PERSONAL.XLSB so I can call it from any of my workbooks.

The version of NextFileName() here is not my latest version. A year ago I encountered a need to handle file versions based on dates and created a new version of NextFileName() that handles such filenames. I located my old version and enhanced it to add “ V2” if no version number was found.

You can run TestNextFileName() to check my routine performs as you would wish.

Option Explicit
Sub TestNextFileName()

    Debug.Print ("AAA 5.abc     -> " & NextFileName("AAA 5.abc"))
    Debug.Print ("BBB V9.abc    -> " & NextFileName("BBB V9.abc"))
    Debug.Print ("CCC V05.abc   -> " & NextFileName("CCC V05.abc"))
    Debug.Print ("DDD V1.99.abc -> " & NextFileName("DDD V1.99.abc"))
    Debug.Print ("EEE.abc       -> " & NextFileName("EEE.abc"))

End Sub
Public Function NextFileName(ByVal CrntFileName As String) As String

  ' * CrntFileName should be of the format "zzzzyy.xxx" where
  '     yy represents a string of one or more decimal digits
  '     the final z is anything but a decimal digit.
  '     xxx represents the extension
  ' * If CrntFileName is of this format, the routine returns "zzzzww.xxx" where
  '     ww is one more than yy.
  ' * If CrntFileName is not of this format. the routine returns "zzzz V2.xxx".
  ' * Examples:
  '     AAA 5.abc      -> AAA 6.abc
  '     BBB V9.abc     -> BBB V10.abc
  '     CCC V05.abc    -> CCC V06.abc
  '     DDD V1.99.abc  -> DDD V1.100.abc
  '     EEE.abc        -> EEE V2.abc
  ' 26Jul11  Coded and tested under VB 2010.
  ' 22Nov11  Amended for VBA
  ' 14Jan19  Became obsolete when version that allowed for other options coded.
  ' 16Apr20  Resurrected in response to SO question.  Amended to add V2 if no
  '          version number found

  Dim Extn As String
  Dim Name As String
  Dim Pos As Integer
  Dim Version As String

  ' Split CrntFileName into name and extension
  Pos = InStrRev(CrntFileName, ".")
  If Pos = 0 Then
    Name = CrntFileName
    Extn = ""
  Else
    Name = Mid(CrntFileName, 1, Pos - 1)
    Extn = Mid(CrntFileName, Pos)       ' Includes dot
  End If

  Pos = Len(Name)
  Do While True
    If IsNumeric(Mid(Name, Pos, 1)) Then
      Pos = Pos - 1
    Else
      Pos = Pos + 1
      Exit Do
    End If
    Loop
  ' If Pos > Len(Name), there are no trailing digits
  ' if Pos <=Len(Name), Pos identifies the first or only trailing digit.

  If Pos > Len(Name) Then
    NextFileName = Name & " V2" & Extn
  Else
    Version = Mid(Name, Pos) + 1      ' Next version number
    ' Add leading zeros if necessary to pad to original length
    Do While Len(Version) < Len(Mid(Name, Pos))
      Version = "0" & Version
    Loop
    NextFileName = Mid(Name, 1, Pos - 1) & Version & Extn
  End If

End Function

Upvotes: 1

Related Questions