vba打开共享文件夹中最近的文件

vba打开共享文件夹中最近的文件,vba,outlook,Vba,Outlook,我想打开共享文件夹中的最新文件。我有一个代码,当我要求检查笔记本电脑文件夹中的文件时,它可以完美地工作,比如“下载”。。。但我必须在共享驱动程序中打开一个文件夹,然后复制此工作簿的信息并粘贴到另一个文件中 在这里,你可以看到我现在拥有的一切 'Force the explicit declaration of variables Option Explicit Sub OpenLatestFile() 'Declare the variables Dim MyPath As

我想打开共享文件夹中的最新文件。我有一个代码,当我要求检查笔记本电脑文件夹中的文件时,它可以完美地工作,比如“下载”。。。但我必须在共享驱动程序中打开一个文件夹,然后复制此工作簿的信息并粘贴到另一个文件中

在这里,你可以看到我现在拥有的一切

'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
“强制显式声明变量
选项显式
子OpenLatestFile()
'声明变量
将MyPath设置为字符串
将MyFile设置为字符串
将最新文件设置为字符串
将LatestDate变为Date
Dim LMD作为日期
'指定文件夹的路径
MyPath=“P:\GTS\zdss\”
'确保路径以反斜杠结束
如果正确(MyPath,1)“\”则MyPath=MyPath&“\”
'从文件夹中获取第一个Excel文件
MyFile=Dir(MyPath&“*.xls”,vbNormal)
'如果未找到任何文件,请退出子目录
如果Len(MyFile)=0,则
MsgBox“未找到任何文件…”,请使用感叹号
出口接头
如果结束
'循环浏览文件夹中的每个Excel文件
当Len(MyFile)>0时执行
'将当前文件的日期/时间分配给变量
LMD=FileDateTime(MyPath&MyFile)
'如果当前文件的日期/时间大于最新日期/时间
'记录日期,将其文件名和日期/时间分配给变量
如果LMD>最晚日期,则
LatestFile=MyFile
LatestDate=LMD
如果结束
'从文件夹中获取下一个Excel文件
MyFile=Dir
环
'打开最新的文件
工作簿。打开MyPath和LatestFile
端接头

这里有三个想法。我不确定是否有人能解决你的问题,但也许它能帮助你

1) 我在论坛()上发现了这一讨论。据我所知,这个问题似乎与你的看法相近。也许可以尝试使用使用的几行代码来管理错误(从错误恢复开始,下一步)

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

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

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

If DateDiff("d",LatestDate,LMD) > 0 Then
当然,您需要更改参数“d”(表示天),以防需要在其他单位中进行比较


干杯。

FileDateTime
即使在共享位置,也必须返回正确的日期。你测试过它返回什么吗<代码>调试.打印LMD。如果它按预期返回,可能必须检查并调整默认日期配置。。。
If DateDiff("d",LatestDate,LMD) > 0 Then