[英]VBA Loop through Directory - Store Results & Sort - Use Array?
我正在嘗試編寫一些VBA代碼(將在Outlook中運行),這些代碼將遍歷目錄並返回文件路徑和滿足特定條件的文件的上次修改日期。 我的經驗有限,根本沒有使用過陣列。
不知道它是否是最好的方法,但是下面的測試代碼是否會輸出我需要的文件路徑和日期。
Sub LoopFiles()
Dim strFolder As String
Dim strFile As String
Dim strDirRef As String
strFolder = "C:\Users\T400\Documents\MacroCROtest\"
strFile = "*Test*" ''''criteria / partial file name
strDirRef = Dir(strFolder & strFile)
Do While Len(strDirRef) > 0
Debug.Print FileDateTime(strFolder & strDirRef) & " " & strFolder & strDirRef
'> OUTPUT = 5/23/16 10:25:59 AM C:\Users\T400\Documents\MacroCROtest\TEST 1.pdf
strDirRef = Dir
Loop
End Sub
我現在需要一種存儲結果的方法-然后需要按日期對結果進行排序。 我只希望在運行代碼時選擇4-5個文件,並且不確定是否(需要?)將它們存儲在數組中,或者是否可以存儲在一系列字符串中。 我試圖找出如何將返回的數據分配給具有以下所示代碼變體的字符串-但無法正常工作。
Do While Len(strDirRef) > 0
i = i + 1
strFound(i) = strDirRef
如何存儲和排序返回的數據?
至於存儲,請參見這兩個不同的選項
Option Explicit
Sub LoopFiles()
Dim strFolder As String
Dim strFile As String
Dim strDirRef As String
Dim nFiles As Long, i As Long
Dim strFound() As String
strFolder = "C:\Users\T400\Documents\MacroCROtest\"
strFile = "*Test*" ''''criteria / partial file name
strDirRef = Dir(strFolder & strFile)
Do While Len(strDirRef) > 0
nFiles = nFiles + 1
ReDim Preserve strFound(1 To nFiles)
strFound(nFiles) = strDirRef
strDirRef = Dir
Loop
For i = 1 To nFiles
MsgBox strFound(i)
Next i
End Sub
Sub LoopFiles2()
Dim strFolder As String
Dim strFile As String
Dim strDirRef As String
Dim nFiles As Long
Dim strFoundStr As String
Dim strFoundArr As Variant
Dim strElem As Variant
strFolder = "C:\Users\T400\Documents\MacroCROtest\"
strFile = "*Test*" ''''criteria / partial file name
strDirRef = Dir(strFolder & strFile)
Do While Len(strDirRef) > 0
strFoundStr = strFoundStr & strDirRef & " "
strDirRef = Dir
Loop
strFoundArr = Split(Trim(strFoundStr)) '<~~ use Split() function to return an array fo strings
For Each strElem In strFoundArr
MsgBox strElem
Next strElem
End Sub
至於數組排序,那么這里有很多代碼:谷歌搜索
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.