删除指定文件夹中的Excel文件

时间:2019-06-29 13:33:16

标签: excel vba

我是VBA的新手,我练习了一些有关删除带有条件的指定文件夹中的Excel文件的代码(如果单元格A2没有数据,则删除Excel文件)。我的代码如下:

Public Sub Deletefile()
    Dim myfolder As String
    Dim myfile As Variant
    Dim i As Variant

    myfolder = "C:\Users\Downloads\AttachmentFolder"
    myfiles = Dir(myfolder & "*.xlsx")
    For i = 1 To UBound(myfiles)
        With Workbooks(i)
            .Open
        End With
        If Workbooks(i).Range("A2").Count = 0 Then
            Kill myfiles(i)
        End If
    Next
End Sub

我在Internet上使用了上面的代码并对其进行了修改,但VBA只是说“类型不匹配”。请更正并解释我错了。

1 个答案:

答案 0 :(得分:0)

这将为您服务:

如果要在第一个工作表之外的其他工作表上检查A2的值,请更改工作表名称。

Public Sub Deletefile()

    Dim myfolder As String

    Dim objFSO As Object
    Dim objFolder, sfol As Object
    Dim objFile As Object

    myfolder = "C:\Users\Downloads\AttachmentFolder\"

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.getFolder(myfolder)

    For Each objFile In objFolder.Files
        If Right(objFile.Name, 5) = ".xlsx" Then
            Workbooks.Open (objFile)

            If Len(ActiveWorkbook.Worksheets(1).Range("A2")) < 1 Then
                ActiveWorkbook.Close False
                Kill objFile
            End If

            ActiveWorkbook.Close False

        End If

    Next objFile

End Sub