首页 > 解决方案 > 遍历文件夹中的所有 Excel 工作簿并将所有公式转换为值

问题描述

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

标签: vbaexcel

解决方案


使用以下代码循环遍历用户指定文件夹中的所有工作簿并执行以下操作:

  1. 它打开工作簿

  2. 它在工作簿中的每个工作表(包括隐藏的工作表)内循环,并将每个包含公式的单元格转换为值。

  3. 执行转换后,它会保存并关闭工作簿,然后转到文件夹中的下一个工作簿。

请参见下面的代码:

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

循环访问某个文件夹中所有工作簿的代码基于以下代码


推荐阅读