在文件夹中查找最新文件并打开它(vba访问)

时间:2014-08-25 17:06:03

标签: vba ms-access

我尝试使用以下代码通过按钮宏在文件夹中打开最新文件。

使用if语句测试,我没有看到任何问题。但是,一旦我使用do,我收到运行时间6的溢出错误消息。

len(dir())无法使用循环吗?

以下是我的代码。

Private Sub Command4_Click()
Dim ~~~~ As Object
Set ~~~~ = CreateObject("Excel.Application")
Dim path As String
Dim name As String
Dim count As Long
Dim number As Long


path = "C:\Users\~~~~~\Desktop\~~~~~~~~~~~~\"
number = Len(Dir(path & "~~~~~~~ - " & Format(Now() - count, "MMMM dd, yyyy") & ".xlsm"))

Do While number = 0
count = count + 1
Loop

~~~~~.workbooks.Open path & "~~~~~~~ - " & Format(Now() - count, "MMMM dd, yyyy") & ".xlsm"


End Sub
由于机密性,〜行只是占位符。

非常感谢。

2 个答案:

答案 0 :(得分:8)

你只是进入堆栈溢出,因为你的循环没有终点。只要number = 0,它就会继续运行,因为在循环中变量号总是等于0,所以循环永远不会停止。你应该将一些绑定到你的while循环中,以便在它中断时达到某个终点或根本不使用它。你想要实现的目标可能是以下

Function NewestFile()

Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
Dim FileSpec As String

'Specify the file type, if any
 FileSpec = "*.*" 
'specify the directory
 Directory = "C:"
FileName = Dir(Directory & FileSpec)

If FileName <> "" Then
    MostRecentFile = FileName
    MostRecentDate = FileDateTime(Directory & FileName)
    Do While FileName <> ""
        If FileDateTime(Directory & FileName) > MostRecentDate Then
             MostRecentFile = FileName
             MostRecentDate = FileDateTime(Directory & FileName)
        End If
        FileName = Dir
    Loop
End If

NewestFile = MostRecentFile

End Function

当循环遍历所有文件时,此循环将停止。

答案 1 :(得分:0)

这是我最终使用的代码。它工作正常但我希望没有与内存泄漏或安全性或其他东西相关的其他问题。

Private Sub Command4_Click()
Dim ~ As Object
Set ~ = CreateObject("Excel.Application")
Dim path As String
Dim count As Long
Dim number As Long

path = "C:\Users\fkong\Desktop\~\"
count = 0

Do While Len(Dir(path & "~ - " & Format(Now() - count, "mmm dd, yyyy") & ".xlsm")) = 0
number = Len(Dir(path & "~ - " & Format(Now() - count, "mmm dd, yyyy") & ".xlsm"))
count = count + 1
Loop

~.Visible = True

~.workbooks.Open path & "~ - " & Format(Now() - count, "mmm dd, yyyy") & ".xlsm"
End Sub