首页 > 解决方案 > 文件夹不可用

问题描述

我正在家里使用 Access 项目工作。我有一个与客户的 VPN 连接,如果我不使用它,它会在 15 分钟后超时。如果 VPN 启动,我下面的代码可以正常工作。如果 VPN 关闭,代码会卡住 60 秒,检查不可用的文件夹。有没有办法将其更改为说 5 秒并“做其他事情”。

Sub check()
Dim fso As New FileSystemObject
    If fso.FolderExists("z:\abc") Then
        'do something
    else
        'do something else
    End If
End Sub

标签: vbams-access

解决方案


您实际上可以在不 ping 服务器的情况下通过使用第二个进程来测试文件夹是否存在来实现这一点。例如,当路径可能引用或可能不引用网络共享时,这是相关的。

代码启动一个 PowerShell 进程以检查文件是否存在,然后等待一段时间以使该 PowerShell 进程完成,否则继续前进。

这种方法的另一个优点是您可以DoEvents在等待时调用,这将防止 Access 锁定,即使在等待您设置的超时时也是如此。

缺点是如果预期的运行时间很短,这将导致相当大的开销。

Dim strPath As String
strPath = "Z:\abc"
Dim cmd As String
cmd = "powershell.exe -c Test-Path '" & Replace(strPath, "'", "''") & "'"
Dim shellobj As Object
Set shellobj = CreateObject("WScript.Shell")
Dim cmdObject As Object
Set cmdObject = shellobj.Exec(cmd)
Dim startTime As Single
startTime = Timer()
Dim fileExists As Boolean
Dim timeoutReached As Boolean
Do While cmdObject.Status = 0
    If Timer() - startTime > 30 Then
        timeoutReached = True
        Exit Do
    End If
    DoEvents
Loop
If Not timeoutReached Then
    fileExists = Trim(cmdObject.StdOut.ReadAll) = "True" & vbCrLf
End If

推荐阅读