我正在尝试根据文件名的起始字符删除文件。
我有一个 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
要检查某个值是否包含在已知列表中,我喜欢使用 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
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