Sub 自动修复测试() Dim strFolder As String, strFile As String, wbk As Workbook Dim wsh As Worksheet, I As Long Application.ScreenUpdating = False With Application.FileDialog(4) If .Show Then strFolder = .SelectedItems(1) Else MsgBox "You haven't selected a folder!", vbExclamation Exit Sub End If End With If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\" End If Dim wbName As String, arrWb, subFoldNew As String subFoldNew = strFolder & "RecoveredWB" strFile = Dir(strFolder & "*.xlsx") Do While strFile <> "" Set wbk = Workbooks.Open(strFolder & strFile, CorruptLoad:=xlRepairFile) For Each wsh In wbk.Worksheets Next wsh arrWb = Split(wbk.FullName, "\") 'place the full name in an array split by "\" wbName = arrWb(UBound(arrWb)) 'the workbook name (without path) 'create RecoveredWB folder if not existing: If Dir(subFoldNew, vbDirectory) = "" Then MkDir subFoldNew wbk.SaveCopyAs subFoldNew & "\" & wbName wbk.Close SaveChanges:=True strFile = Dir Loop Application.ScreenUpdating = True Exit Sub Err_Open: Err.Clear Application.ScreenUpdating = True End Sub 这个VBA只能修复一个xlsx文件,文件夹下剩余文件没有循环生成
时间: 2024-04-22 15:26:15 浏览: 253
对不起,我之前给出的代码确实只能修复一个 `.xlsx` 文件,而没有循环处理文件夹下的其他文件。为了修复文件夹中的所有文件,你需要对代码进行一些修改。下面是修复文件夹中所有 `.xlsx` 文件的 VBA 代码示例:
```vba
Sub AutoRepairFilesInFolder()
Dim sourceFolder As String
Dim destinationFolder As String
Dim fileName As String
Dim wb As Workbook
sourceFolder = "C:\SourceFolderPath\" ' 设置源文件夹路径
destinationFolder = "C:\DestinationFolderPath\" ' 设置目标文件夹路径
' 检查源文件夹是否存在
If Dir(sourceFolder, vbDirectory) = "" Then
MsgBox "Source folder does not exist!", vbExclamation
Exit Sub
End If
' 创建目标文件夹
If Dir(destinationFolder, vbDirectory) = "" Then
MkDir destinationFolder
End If
' 获取源文件夹中的第一个文件
fileName = Dir(sourceFolder & "*.xlsx")
' 循环处理源文件夹中的所有文件
Do While fileName <> ""
' 打开文件并尝试修复
Set wb = Workbooks.Open(sourceFolder & fileName, CorruptLoad:=xlRepairFile)
' 保存修复后的文件到目标文件夹
wb.SaveAs destinationFolder & Left(fileName, Len(fileName) - 5) & "_Repaired.xlsx"
' 关闭文件
wb.Close SaveChanges:=False
' 获取下一个文件
fileName = Dir
Loop
MsgBox "Files repaired and saved to the destination folder.", vbInformation
End Sub
```
在这个示例中,你需要设置 `sourceFolder` 变量为源文件夹的路径,将 `destinationFolder` 变量设置为目标文件夹的路径。代码会检查源文件夹是否存在,并创建目标文件夹(如果不存在)。然后,它会循环处理源文件夹中的所有 `.xlsx` 文件,打开并尝试修复它们,然后将修复后的文件保存到目标文件夹中。
请确保在运行代码之前备份好源文件夹中的文件,以免出现意外情况。
阅读全文