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

fra*_*cis 4 ms-access vba

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

使用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
Run Code Online (Sandbox Code Playgroud)

由于机密性,〜行只是占位符.

非常感谢你.

geo*_*rge 9

你只是进入堆栈溢出,因为你的循环没有终点.只要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
Run Code Online (Sandbox Code Playgroud)

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