【问题标题】:finding latest file in a folder and opening it (vba access)在文件夹中查找最新文件并打开它(vba 访问)
【发布时间】:2018-02-09 20:31:37
【问题描述】:

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

使用 if 语句测试,我没有发现任何问题。但是一旦我使用 do while,我会收到运行时 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

由于保密原因,~ 行只是占位符。

非常感谢。

【问题讨论】:

  • 我建议添加对 Microsoft 脚本运行时(工具、参考...)的引用,并使用 FileSystemObject 查找您要查找的文件。请注意,您的代码使用 Excel,但标签是 MS Access。除非你真的需要,否则我不会使用 Excel 自动化。您可以使用 Shell 方法来启动 xls 文件。

标签: vba ms-access


【解决方案1】:

您只是进入堆栈溢出,因为您的循环没有终点。只要 number = 0,它将继续运行,并且由于在循环中变量 number 始终等于 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

当它遍历所有文件时,这个循环将停止。

【讨论】:

  • 非常感谢您的意见。我忘了在 do while 循环中移动边界条件哈哈。我实际上只是在寻找该命名格式的文件,因为所有以前的文件实际上都已存档。
  • 在循环中,我希望FileName = Dir(Directory)?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    相关资源
    最近更新 更多