0
votes

I am looking for a VBA code that would allow me to loop through all the Excel workbooks in a certain folder, and for each workbook will convert the cells in each worksheet from formulas to values.

1
This is not the place to look. We can help you fix your code but we aren't here to write it for you.nicomp

1 Answers

1
votes

Use the following code which loops through all the workbooks in a user-specified folder and does the following:

  1. It opens the workbook

  2. It loops within each worksheet in the workbook (including hidden worksheets), and converts to values every cell that contains a formula.

  3. After performing the conversion, it saves and closes the workbook, and moves on to the next workbook in the folder.

See code below:

Sub LoopAllExcelFilesInFolderCancelFormulas()
'Purpose: To loop through all Excel files in a user specified folder and convert all formulas to values
Dim wb As Workbook
Dim ws As Worksheet
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Disable Excel Pop-up messages:
Application.DisplayAlerts = False

'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

   For Each ws In wb.Sheets
       ws.UsedRange.Value = ws.UsedRange.Value
   Next

   'Save and Close Workbook
   wb.Close SaveChanges:=True

   '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.DisplayAlerts = True

End Sub

The code for looping through all workbooks in a certain folder is based on the following code.