excelvbawhile-loopdelete-file

Check if file starts with values from list and if not kill it


I am trying to delete files based on the file name's starting characters.

I have an Excel file with numbers in column A. These numbers are either 4, 5 or 6 digits.

I have a file folder with files which may not start with these digits from a range from Excel file.
These files in folders are of different types.

The naming convention:
4563_listofitems.pdf,65475_skusdec.doc etc.

My goal is to loop through files and check if the starting characters of the file are included in the A range of the Excel sheet.
If so (there may be up to six files starting with such number) create a folder named with the found starting characters and move the files into the folder.
Else delete (kill) that file.

How do I check the files names against the list?

My code for looping

Sub loopf

Dim filen as variant
Filen =dir("c:\test\")

While filen <>""
    If instr(1,filen,10000)=1 then
        'Here I want check against the values from range but unsure how ,should I somehow loop through the range ?
        Filen=dir
    End if
Wend

End sub

Solution

  • To check if a value is contained within a known list, I like using the Dictionary Object. It has the function Exists which checks if a value is listed within the Dictionary.

    So before you loop through the files, you just need to add every one of your accepted numbers into the dictionary. Then while looping though the files check if Dictionary.Exists(Value). If it exists, then the value is good, if not then Kill.

    Here's how I would set that up:

    Sub loopf()
        Dim AcceptedPrefixes As Object
        Set AcceptedPrefixes = CreateObject("Scripting.Dictionary")
        
        Dim PrefixRange As Range
        Set PrefixRange = ThisWorkbook.Sheets(1).Range("A1:A5")
        
        Dim Cell As Range
        For Each Cell In PrefixRange.Cells
            If Cell <> "" And Not AcceptedPrefixes.exists(Cell.Value) Then
                AcceptedPrefixes.Add CStr(Cell.Value), 0
            End If
        Next
    
        Dim Directory As String
        Directory = "c:\test\"
    
        Dim filen As Variant
        filen = Dir(Directory)
        While filen <> ""
            Dim FilePrefix As String
            FilePrefix = Split(filen, "_")(0)
            
            If Not AcceptedPrefixes.exists(FilePrefix) Then
                Kill Directory & filen
            End If
            
            filen = Dir
        Wend
    End Sub