vba - 遍历文件夹中的所有 Excel 工作簿并将所有公式转换为值
问题描述
我正在寻找一个 VBA 代码,它允许我遍历某个文件夹中的所有 Excel 工作簿,并且对于每个工作簿,将每个工作表中的单元格从公式转换为值。
解决方案
使用以下代码循环遍历用户指定文件夹中的所有工作簿并执行以下操作:
它打开工作簿
它在工作簿中的每个工作表(包括隐藏的工作表)内循环,并将每个包含公式的单元格转换为值。
执行转换后,它会保存并关闭工作簿,然后转到文件夹中的下一个工作簿。
请参见下面的代码:
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
循环访问某个文件夹中所有工作簿的代码基于以下代码。
推荐阅读
- servlets - AEM 6.3 - 请求的路径 *.servlet 不在可用的搜索路径中/500 服务器错误
- python - MapReduce Python,似乎无法将标准传送到文本文件
- regex - 如何提取仅匹配该行中第一次出现的特定字符的每一行?
- vue.js - Vue-bootstrap 嵌套复选框
- swift - Swift 4 KeyPath 处理不同类型的对象
- unit-testing - 监视 Golang 中的方法
- excel - VBA:收到运行时错误“13”:类型不匹配
- opencv - 我可以使用 OpenCV 分析视频中人脸在屏幕中央的长度吗?
- html - 在选择表单中制作第一个选项的颜色,以及可点击的字体真棒
- php - 从 XML 文件接收特定值