[英]Excel VBA: Delete any empty Excel file in folder
I'd like to be able to search a folder of .xls
files and delete any file from the folder that is empty.我希望能够搜索
.xls
文件的文件夹并从空文件夹中删除任何文件。 When I say empty, I mean there are either no sheets in the file or there is not any data in any cells, if a sheet does exist.当我说空时,我的意思是文件中没有工作表,或者任何单元格中都没有任何数据(如果工作表确实存在)。
CODE:代码:
Sub DeleteEmptyFiles()
Dim FolderPath As String
Dim Filename As String
Dim ws As Worksheet
Application.ScreenUpdating = False
FolderPath = "Enter the folder path here"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each ws In ActiveWorkbook.Sheets
'DELETE FILE IF EMPTY
Next ws
Workbooks(Filename).Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each ws In ActiveWorkbook.Sheets
If Application.WorksheetFunction.CountA(ws.Cells()) > 0 Then
MsgBox "the Sheet " & ws.Name & " contents data "
Exit For
Else
MsgBox "no data in " & ws.Name
End If
Next ws
Workbooks(Filename).Close
Filename = Dir()
Loop
Try the next way, please:请尝试下一种方法:
Sub DeleteEmptyFiles()
Dim FolderPath As String, Filename As String, wb As Workbook
Dim ws As Worksheet, boolNotEmpty As Boolean
Dim previousSecurity As MsoAutomationSecurity
FolderPath = "Enter the folder path here" 'Take care to end the folder path in "\"
'Otherwise, build the file full name inserting "\"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
previousSecurity = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Set wb = Workbooks.Open(Filename:=FolderPath & Filename)
Application.AutomationSecurity = previousSecurity
boolNotEmpty = False
For Each ws In wb.Worksheets
If WorksheetFunction.CountA(ws.UsedRange) > 0 Then
boolNotEmpty = True: Exit For
End If
Next ws
wb.Close False
If Not boolNotEmpty Then Kill FolderPath & Filename
Filename = Dir()
Loop
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.