VBA|获取常用的路径并按照选择的路径打开指定的文件夹-windows无法访问指定设备路径或文件

VBA|获取常用的路径并按照选择的路径打开指定的文件夹-windows无法访问指定设备路径或文件

1 获取常用的路径

Sub getPath()

Range("A1") = "路径名称"

Range("B1") = "具体路径"

Range("A2") = "SystemDrive"

Range("B2") = Environ("SystemDrive")

Range("A3") = "TEMP"

Range("B3") = Environ("TEMP")

Range("A4") = "windir"

Range("B4") = Environ("windir")

Range("A5") = "SystemRoot"

Range("B5") = Environ("SystemRoot")

Range("A6") = "ProgramFiles"

Range("B6") = Environ("ProgramFiles")

Range("A7") = "Application.path"

Range("B7") = Application.Path

Range("A8") = "Application.StartupPath"

Range("B8") = Application.StartupPath

Range("A9") = "Application.TemplatesPath"

Range("B9") = Application.TemplatesPath

Range("A10") = "Application.UserLibraryPath"

Range("B10") = Application.UserLibraryPath

Range("A11") = "Application.DefaultFilePath"

Range("B11") = Application.DefaultFilePath

Range("A12") = "Application.NetworkTemplatesPath"

Range("B12") = Application.NetworkTemplatesPath

End Sub

运行结果:

路径变量具体路径
SystemDriveC:
TEMPC:\Users\WWUHNW~1\AppData\Local\Temp
windirC:\Windows
SystemRootC:\Windows
ProgramFilesC:\Program Files
Application.pathC:\Program Files\Microsoft Office\Office12
Application.StartupPathC:\Users\\username\AppData\Roaming\Microsoft\Excel\XLSTART
Application.TemplatesPathC:\Users\\username\AppData\Roaming\Microsoft\Templates\
Application.UserLibraryPathC:\Users\\username\AppData\Roaming\Microsoft\AddIns\
Application.DefaultFilePathC:\Users\\username\Documents

2 按照选择的路径打开指定的文件夹

选中地址所在单元格,运行下述代码即可打开指定的文件夹。

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal sParam As Long, ByVal lParam As Long) As Long

Private Const WM_CLOSE As Long = &H10

'以上代码声明API函数和常量

Public Sub OpenDirectory()

Dim path1 As String

path1 = ActiveCell

ShellExecute 0, "", "", "", path1, 1

End Sub

Public Sub CloseDirectory()

Dim hWnd As Long

hWnd = FindWindows(vbNullString, "C:\Program Files\Microsoft Office\Office12")

PostMessage hWnd, WM_CLOSE, 0, 0

End Sub

推荐阅读