简体   繁体   中英

Loop through all excel workbooks in a folder and convert all formulas to values

我正在寻找一个VBA代码,该代码将允许我遍历某个文件夹中的所有Excel工作簿,并且对于每个工作簿,会将每个工作表中的单元格从公式转换为值。

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM