2017-11-11 245 views
0

我在指定的路径上下载文件,但每次打开最近的文件时,我都必须将最近的文件重命名为我已设置的指定名称宏。Excel VBA:如何打开最近的excel文件

只要文件的路径没有改变,我希望宏打开最近的文件。例如,给定两个文件my_file_fb和my_file_fb(1),我想打开最近下载的文件。

+0

那么,你可以使用[FileDateTime()](https://www.techonthenet.com/excel/formulas/filedatetime.php)来获取文件的创建日期,[Dir](https:// stackoverflow .com/a/10382861/6609896)以循环遍历文件。然后只需比较日期即可找到最近的日期。 – Greedo

+0

你能写代码吗?也许是一个例子。 – Kaleembukhari

+0

那么你到目前为止尝试过什么?你用什么代码来比较返回的日期,或打开文件? SO在这里并不是真正的代码编写服务,所以最好展示你迄今为止所做的工作。尝试使用我建议的链接编写一些内容,并解释你刚刚陷入困境的位置。 – Greedo

回答

1

按我的意见,这个功能应该做的伎俩:

Public Function MostRecentFile(ByVal searchDirectory As String, ByVal wildCard As String) As String 
    '''Returns the most recent file in searchDirectory, which matches wildCard criteria 
    Dim strFile As String      'holds the name of the file we're currently looking at 
    Dim mostRecent As Date      'holds the date of creation for the most recent file 
    Dim currDate As Date       'date of creation for the current file 
    Dim mostRecentPath As String     'path of file with most recent date 

    strFile = Dir(searchDirectory & wildCard) 'look for file in directory which matches wildcard 
    Do While Len(strFile) > 0     'loop until Dir returns empty quotes (no files) 
     currDate = FileDateTime(searchDirectory & strFile) 
     If currDate > mostRecent Then   'check whether current file is more recent than previous files 
      mostRecent = currDate    'if so, update most recent date and file 
      mostRecentPath = searchDirectory & strFile 
     End If 
     strFile = Dir       'move to next file in directory 
    Loop 

    If mostRecent = 0 Then      'check whether any files were returned 
     MostRecentFile = "No files match '" & searchDirectory & wildCard & "'" 
    Else 
     MostRecentFile = mostRecentPath 
    End If 
End Function 

这需要输入字符串searchDirectorywildCard,第一个指定要看看在哪个文件夹,第二个指定文件搜索的类型。

例如

MostRecentFile("C:/Users/[USERNAME]/Downloads/", "*.xls") 

返回路径从".xlsm",".xls",".xlsx"最近的文件(Excel文件)在您的下载文件夹作为String

我已经添加代码注释,所以希望您能够了解每一步都做

+0

非常感谢。我会试一试。 顺便说一下,我试着使用Dir函数。该代码运行时没有错误,但是,它不会在msg框中返回任何文件名。这是语法。 excel_file = Dir(“Macintosh HD:Users:kaleembukhari:Documents”,MacID(“Sting.xls:”)) – Kaleembukhari

+0

@Kaleembukhari Ahh,这种方法不适用于Mac,因为'DIR'不适用于通配符苹果电脑。你将不得不搜索该网站的mac答案。 [本工作手册](https://www.rondebruin.nl/mac/mac013.htm)可能会有所帮助。但是您必须在您的问题中始终使用[excel-vba-mac](https://stackoverflow.com/questions/tagged/excel-vba-mac)标签(或同等标签),因为这是许多答案中的重要信息 – Greedo