使用VBA如何确定路径是否指向本地硬盘驱动器或网络上的某个位置?

使用VBA如何确定路径是否指向本地硬盘驱动器或网络上的某个位置?,vba,Vba,当用户将网络驱动器作为保存宏生成的文件的位置时,我会遇到性能问题 为了提高效率,我考虑确定该位置是本地还是网络上,如果在网络上,我将使用宏将生成的文件保存到临时文件夹中,并在生成后将其移动 使用VBA如何确定路径M:\Folder Name\是本地文件夹(易于操作)还是在网络上(通过VPN处理请求需要很长时间)?您可以使用API函数GetDriveTypeA-请参阅 将以下代码放入模块中。您可以使用函数getDriveType获取描述驱动器类型的字符串,也可以使用函数isNetworkDrive

当用户将网络驱动器作为保存宏生成的文件的位置时,我会遇到性能问题

为了提高效率,我考虑确定该位置是本地还是网络上,如果在网络上,我将使用宏将生成的文件保存到临时文件夹中,并在生成后将其移动


使用VBA如何确定路径
M:\Folder Name\
是本地文件夹(易于操作)还是在网络上(通过VPN处理请求需要很长时间)?

您可以使用API函数
GetDriveTypeA
-请参阅

将以下代码放入模块中。您可以使用函数
getDriveType
获取描述驱动器类型的字符串,也可以使用函数
isNetworkDrive
简单地检查驱动器号是否指向网络驱动器

您可以将文件夹或文件的全名作为参数传递,例程只接受第一个字符并添加
:\
。例如,可以这样称呼它:

If isNetworkDrive("M:\Folder Name\") Then
    MsgBox "This is a network drive"
End If
若要使其更复杂,请首先检查参数是否为UNC路径(从
\\
开始)


底层函数是
GetDriveType

确定磁盘驱动器是否为可移动、固定、CD-ROM、RAM 磁盘或网络驱动器

Option Explicit

#If VBA7 Then
Declare PtrSafe Function apiGetDriveType Lib "kernel32" Alias "GetDriveTypeA" (ByVal nDrive As String) As Long
#Else
Declare Function getDriveType Lib "kernel32" Alias "GetDriveTypeA" (ByVal nDrive As String) As Long
#End If

Function isNetworkDrive(path As String) As Boolean
    Dim driveType As Integer
    driveType = apiGetDriveType(getDrivePath(path))
    isNetworkDrive = (driveType = 4)
End Function

Function getDriveType(path As String) As String
    ' See https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdrivetypea
    Dim driveType As Integer
    driveType = apiGetDriveType(getDrivePath(path))
    
    If driveType = 0 Then
        getDriveType = ""               ' Drive unknown.
    ElseIf driveType = 1 Then
        getDriveType = "(undefined)"               ' No Root (not mounted?)
    ElseIf driveType = 2 Then
        getDriveType = "Removable"
    ElseIf driveType = 3 Then
        getDriveType = "Fixed"
    ElseIf driveType = 4 Then
        getDriveType = "Network"
    ElseIf driveType = 5 Then
        getDriveType = "CD-Rom"
    ElseIf driveType = 6 Then
        getDriveType = "Ram Disk"
    Else
        getDriveType = ""               ' Can never happen according to documentation
    End If
End Function

Function getDrivePath(ByVal path As String)
    GetDrivePath = UCase(Left(path, 1)) & ":\"
End Function