在我學習 VBA 的永無止境的故事中,我試圖創建一個宏,該宏根據檔案的起始字符洗掉檔案,但不確定如何繼續。
我有一個在 a 列中有數字的 excel 檔案,這些數字是 4,5 或 6 位數字。我有一個檔案夾,其中的檔案可能以也可能不以這些數字開頭,這些數字來自 excel 檔案的范圍。檔案夾中的這些檔案的型別不同
但我認為這可能仍然不是問題,命名約定如下:即。4563_listofitems.pdf,65475_skusdec.doc 等
我的目標是遍歷檔案并檢查檔案的起始字符是否包含在 Excel 作業表的 A 范圍內,如果是(最多可能有 6 個檔案以這樣的數字開頭)創建一個以找到的檔案夾命名的檔案夾開始字符并將以這些字符開頭的檔案移動到檔案夾中,否則如果檔案不是以串列中的固定字符開頭,則只需洗掉(殺死)該檔案。我的問題是如何根據串列檢查檔案名。
我的代碼現在用于回圈槽
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
uj5u.com熱心網友回復:
要檢查某個值是否包含在已知串列中,我喜歡使用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
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/372602.html
