我正在测试是否存在网络文件。
我发现对于某些文件,VBA进程停止并打开调试窗口而没有任何错误,只是突出显示了一行(我在下面指出)。如果我按F5继续,该过程将毫无问题地完成。
FilePath = "\\network\file.pdf"
If Not Dir(FilePath, vbDirectory) = vbNullString Then
' The process gets stuck on the next line
' I need to add a delay to prevent it to stop like: Application.Wait Now + #12:00:05 AM#
Worksheets(valRef).OLEObjects.Add Filename:=FilePath, Link:=False, DisplayAsIcon:=False
Else
' Do something else
End If
似乎在文件很大时会发生。如果我添加一个等待,那么这个过程还可以,但是当我不得不处理许多文件时,我会大大延迟整个过程。有没有办法阻止它停止?
答案 0 :(得分:1)
您可以在下面找到所需的组件:
'To check if a particular file exists
'excelFile = False, if it is not an Excel file that is being checked
Public Function isAnExistingFile(ByVal fileNameStr As Variant, Optional ByVal excelFile As Boolean = True) As Boolean
Dim wb As Workbook
isAnExistingFile = True
On Error Resume Next
If Not VarType(fileNameStr) = vbString Then
isAnExistingFile = False
ElseIf Len(fileNameStr) = 0 Then
isAnExistingFile = False
ElseIf Len(Dir(fileNameStr)) = 0 Then
isAnExistingFile = False
ElseIf ((GetAttr(fileNameStr) And vbDirectory) <> vbDirectory) = False Then
isAnExistingFile = False
Else
If excelFile Then
Set wb = Application.Workbooks.Open(Filename:=fileNameStr, UpdateLinks:=0, ReadOnly:=True)
If wb Is Nothing Then isAnExistingFile = False
If Not wb Is Nothing Then
wb.Close False
Set wb = Nothing
End If
End If
End If
Err.Clear: On Error GoTo 0
End Function