在桌面及其子文件夹上查看实际代码,然后删除csv,xlsm和xlsb。
但是我收到编译错误
对于已在使用的控制变量。
任何想法出了什么问题
Dim FSO As Object
Sub delkillcsv()
Dim myFiles As Object, file As Object
Dim startFold As String
Set FSO = CreateObject("Scripting.FileSystemObject")
startFold = "C:\Test\Demo"
If Right(startFold, 1) = "\" Then
startFold = Left(startFold, Len(startFold) - 1)
End If
Set myFiles = FSO.GetFolder(startFold).Files
For Each file In myFiles
If InStr(file.Name, ".csv") Then
Kill file.Path
End If
Next
For Each file In myFiles
If InStr(file.Name, ".xlsm") Then
Kill file.Path
End If
Next
For Each file In myFiles
If InStr(file.Name, ".xlsb") Then
Kill file.Path
End If
Next
Call chkSubfolder(FSO.GetFolder(startFold))
End Sub
Sub chkSubfolder(fold As Object)
Dim subfolder As Object, fileCol As Object, file As Object
For Each subfolder In fold.Subfolders
Set fileCol = FSO.GetFolder(subfolder.Path).Files
For Each file In fileCol
If InStr(file.Name, ".csv") Then
Kill file.Path
End If
Next
For Each subfolder In fold.Subfolders
Set fileCol = FSO.GetFolder(subfolder.Path).Files
For Each file In fileCol
If InStr(file.Name, ".xlsm") Then
Kill file.Path
End If
Next
For Each subfolder In fold.Subfolders
Set fileCol = FSO.GetFolder(subfolder.Path).Files
For Each file In fileCol
If InStr(file.Name, ".xlsb") Then
Kill file.Path
End If
Next
Call chkSubfolder(subfolder)
Next
End Sub
答案 0 :(得分:1)
你的第二个缺席了两个Next语句。您可以重复使用For ... Next控件,但必须先完成For ... Next,
Sub chkSubfolder(fold As Object)
Dim subfolder As Object, fileCol As Object, file As Object
For Each subfolder In fold.Subfolders
Set fileCol = FSO.GetFolder(subfolder.Path).Files
For Each file In fileCol
If InStr(file.Name, ".csv") Then
Kill file.Path
End If
Next file
Next subfolder '<~~ this was missing
For Each subfolder In fold.Subfolders
Set fileCol = FSO.GetFolder(subfolder.Path).Files
For Each file In fileCol
If InStr(file.Name, ".xlsm") Then
Kill file.Path
End If
Next file
Next subfolder '<~~ this was missing
For Each subfolder In fold.Subfolders
Set fileCol = FSO.GetFolder(subfolder.Path).Files
For Each file In fileCol
If InStr(file.Name, ".xlsb") Then
Kill file.Path
End If
Next file
Call chkSubfolder(subfolder)
Next subfolder
End Sub
如上所述,标记下一个语句并使用常规缩进可以减少这些错误,因为它们变得非常明显。