循环浏览文件夹中的所有excel工作簿并将所有公式转换为值

时间:2018-08-22 22:32:46

标签: excel vba excel-vba

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

1 个答案:

答案 0 :(得分:0)

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

  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

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