检查文件是否以列表中的值开头,如果不是则杀死它

问题描述 投票:0回答:2

我正在尝试根据文件名的起始字符删除文件。

我有一个 Excel 文件,A 列中有数字。这些数字是 4、5 或 6 位数字。

我的文件夹中的文件可能不是以 Excel 文件中的这些数字开头。
文件夹中的这些文件具有不同的类型。

命名约定:
4563_listofitems.pdf,65475_skusdec.doc等

我的目标是循环遍历文件并检查文件的起始字符是否包含在Excel工作表的A范围内。
如果是这样(最多可能有六个以该数字开头的文件)创建一个以找到的起始字符命名的文件夹并将文件移动到该文件夹中。
否则删除(杀死)该文件。

如何根据列表检查文件名?

我的循环代码

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
excel vba while-loop delete-file
2个回答
0
投票

要检查某个值是否包含在已知列表中,我喜欢使用 Dictionary 对象。它具有功能

Exists
,可检查字典中是否列出了某个值。

因此,在循环访问文件之前,您只需将您接受的每一个数字添加到字典中即可。然后在循环文件时检查是否

Dictionary.Exists(Value)
。如果存在,那么价值就很好,如果不存在,那就
Kill

我的设置方法如下:

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

0
投票
Sub Files()
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("C:\test") 
For Each oFile In oFolder.Files
    'do somthing
Next oFile
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.