我在MS Access中使用VBA,其中一个subs在网络中获取文件路径,检查文件是否存在,并在其上写入查询结果。 问题是,当我尝试运行代码时,它给出了错误52(错误的文件名或数字)。但是,如果我首先在Windows资源管理器中打开网络路径,那么之后错误就不再发生了。关于问题可能是什么的任何想法?
以下是我正在运行的一些代码:
fpath = "\\networkpath\file.txt"
DeleteFile fpath
Sub DeleteFile(ByVal FileToDelete As String)
FileExists(FileToDelete) Then
SetAttr FileToDelete, vbNormal
FileToDelete
End If
End Sub
Function FileExists(ByVal FileToTest As String) As Boolean
FileExists = (Dir(FileToTest) <> "") 'this is where the error happens
End Function
答案 0 :(得分:2)
您使用的UNC路径是否包含任何非Ascii字符,例如重音符号?确切的路径是什么?
无论如何,VBA中的任何文件函数都不能很好地与Unicode配合使用。
您可以尝试使用FileSystemObject
来实现与内置VBA函数相同的可靠性:
Public Function FileExists(filePath as string) as Boolean
Dim o As Object
Set o = CreateObject("Scripting.FileSystemObject")
FileExists = o.FileExists(filePath)
End Function
使用Win32 API的替代方案可在32位和64位环境中运行:
Private Const INVALID_FILE_ATTRIBUTES As Long = -1
#If VBA7 Then ' Win API Declarations for 32 and 64 bit versions of Office 2010 and later
Private Declare PtrSafe Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesW" (ByVal lpFileName As LongPtr) As Long
#Else ' WIN API Declarations for Office 2007
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesW" (ByVal lpFileName As Long) As Long
#End If
Public Function FileExists(fname As Variant) As Boolean
If IsNull(fname) Or IsEmpty(fname) Then Exit Function
' Make sure that we can take care of paths longer than 260 characters
If Left$(fname, 2) = "\\" Then
FileExists = GetFileAttributes(StrPtr("\\?\UNC" & Mid$(fname, 2))) <> INVALID_FILE_ATTRIBUTES
Else
FileExists = GetFileAttributes(StrPtr("\\?\" & fname)) <> INVALID_FILE_ATTRIBUTES
End If
End Function