Jer*_*emy 4 excel vba excel-vba
我正在尝试找到一个函数,比如Environ找到我的业务中的主驱动器已经映射到特定PC上的驱动器.
使用文件路径"G:\ Eworking\SET\Operations\file"我知道我的PC已被映射,以便该文件路径在G驱动器内,但其他可能被映射不同,所以我想确定它是什么.
我已经尝试过if else方法来完成字母表并做一个if Dir([filepath]) then之前(见下文),但我想知道是否有更好的方法来做到这一点?
Sub LoopThroughDrives()
sFilePath As String
sFilePath = ":\Eworking\SET\Operations\file"
If Dir("A" & sFilePath) > 0 Then
msgbox ("It's in drive A")
Else
If Dir("B" & sFilePath) > 0 Then
msgbox ("It's in drive B")
Else
If Dir("C" & sFilePath) > 0 Then
msgbox ("It's in drive C")
Else
'...........................
'All other letters of the alphabet, checking each possibility
'...........................
End If
End If
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
你可以得到像这样的驱动器号和路径:
For Each d In CreateObject("Scripting.FileSystemObject").Drives
Debug.Print d.DriveLetter, d.Path, d.ShareName
Next
Run Code Online (Sandbox Code Playgroud)
小智 5
使用ASCII字符的For ... Next循环似乎是合适的.
dim c as integer
for c = 65 to 90
If CBool(Len(Dir(Chr(c) & sFilePath))) Then
msgbox "It's in drive " & Chr(c) '<~~msgbox, not magbox
exit for
end if
next c
if c > 90 then msgbox "never found"
Run Code Online (Sandbox Code Playgroud)