【问题标题】:Open the most recent file in a shared folder打开共享文件夹中的最新文件
【发布时间】:2021-10-23 04:33:54
【问题描述】:

我想打开共享文件夹中的最新文件。

我有一个代码可以检查笔记本电脑文件夹中的文件,例如“下载”,但我必须在共享驱动器中打开一个文件夹,然后复制此工作簿的信息并粘贴到另一个文件中。

'Force the explicit declaration of variables
Option Explicit

Sub OpenLatestFile()

    'Declare the variables
    Dim MyPath As String
    Dim MyFile As String
    Dim LatestFile As String
    Dim LatestDate As Date
    Dim LMD As Date
    
    'Specify the path to the folder
    MyPath = "P:\GTS\zdss\"
    
    'Make sure that the path ends in a backslash
    If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
    
    'Get the first Excel file from the folder
    MyFile = Dir(MyPath & "*.xls", vbNormal)
    
    'If no files were found, exit the sub
    If Len(MyFile) = 0 Then
        MsgBox "No files were found...", vbExclamation
        Exit Sub
    End If
    
    'Loop through each Excel file in the folder
    Do While Len(MyFile) > 0
    
        'Assign the date/time of the current file to a variable
        LMD = FileDateTime(MyPath & MyFile)
        
        'If the date/time of the current file is greater than the latest
        'recorded date, assign its filename and date/time to variables
        If LMD > LatestDate Then
            LatestFile = MyFile
            LatestDate = LMD
        End If
        
        'Get the next Excel file from the folder
        MyFile = Dir
        
    Loop
    
    'Open the latest file
    Workbooks.Open MyPath & LatestFile
        
End Sub

【问题讨论】:

  • FileDateTime 即使在共享位置也必须返回正确的日期。你测试过它返回什么吗? Debug.Print LMD。如果它按预期返回,则可能必须检查并调整默认日期配置...

标签: vba outlook


【解决方案1】:

这里有 3 个想法。我不确定是否有人会解决您的问题,但也许它可以帮助您。

1) 我在论坛 (http://www.vbaexpress.com/forum/showthread.php?19669-Workbooks-Open-using-network-path) 上找到了这个讨论。据我了解,问题似乎与您很接近。也许尝试使用几行来管理错误(从 On Error Resume 开始)。

2) 我想你已经验证过了,但是文件的扩展名是“.xls”,而不是“.xlsx”?

3) 在 VBA 中对日期进行操作需要特定的函数。在这里,您正在进行比较,就好像它是整数一样 (LMD > LatestDate)。此外,我不确定 LatestDate 是否有合适的值,因为你从一开始就没有定义它。我建议以这种方式更改代码。首先在 While 语句之前使用任意低值定义 LatestDate(这样,您可以确定该变量有一个值,并且 If LMD > LatestDate 语句将正常工作)。

LatestDate = Format("01.01.1900", "dd.mm.yyyy")

其次,更改 If LMD > LatestDate 语句:

If DateDiff("d",LatestDate,LMD) > 0 Then

当然,如果你想以其他单位进行比较,你需要更改参数“d”(代表天)。

干杯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多