VBA循环目录 - 存储结果&排序 - 使用数组?

时间:2016-05-23 17:33:34

标签: arrays vba loops

我正在尝试编写一些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

如何存储和排序返回的数据?

1 个答案:

答案 0 :(得分:0)

至于存储看到这两个不同的选项

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

对于排序数组,那里有很多代码:只是google it

相关问题