You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA实现从指定目录获取最新含WIP的Excel文件完整路径

解决VBA查找指定文件夹下最新含"WIP"的Excel文件问题

问题分析

原代码存在两个核心问题:

  • 未用正确的通配符过滤含"WIP"的目标文件
  • 未遍历全部符合条件的文件并通过修改时间筛选最新文件

修正后的完整代码

'Go through Columns, check Country and update formulas
Do While Cells(StartRow, Counter).Value <> Empty
    CurrentCountry = Cells(StartRow, Counter)
    FullPath = FixedFolderPath & CurrentYear & "\" & CurrentCountry & "\" & CurrentMonthPath
    Debug.Print CurrentCountry
    
    '-----------------------------------
    'Checking the most recent WIP file
    Dim latestFile As String
    Dim latestTime As Date
    Dim currentFile As String
    Dim currentFilePath As String
    
    '初始化:获取第一个含WIP的Excel文件
    currentFile = Dir(FullPath & "*WIP*.xls*", vbNormal)
    
    Do While currentFile <> ""
        currentFilePath = FullPath & currentFile
        '比较当前文件修改时间与已记录的最新时间
        If FileDateTime(currentFilePath) > latestTime Then
            latestTime = FileDateTime(currentFilePath)
            latestFile = currentFilePath
        End If
        '获取下一个符合条件的文件
        currentFile = Dir
    Loop
    
    '输出/使用最新文件的完整路径
    If latestFile <> "" Then
        Debug.Print "最新WIP文件路径:" & latestFile
        '这里可添加后续处理逻辑,比如打开文件、更新公式等
    Else
        Debug.Print CurrentCountry & " 未找到含WIP的Excel文件"
    End If
    
    Counter = Counter + 1
Loop

关键逻辑说明

  • 用*WIP*.xls*作为Dir的通配符,精准筛选文件名包含"WIP"的Excel格式文件(支持.xls/.xlsx/.xlsm等)
  • 通过FileDateTime()函数获取文件最后修改时间,遍历过程中持续更新记录最新的文件路径
  • 第一次调用Dir时传入路径和通配符,后续无参数调用Dir会自动遍历剩余符合条件的文件,不会遗漏第一个文件

内容的提问来源于stack exchange,提问作者Atila D. Grings

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:22:39