我在打开文件对话框时尝试指定网络目录,但是我遇到了一些问题。我尝试使用的代码如下:
ChDrive "M:\"
ChDir "\yyy"
驱动器映射为M,因此,如果我替换以下代码,则可以使用:
link_to
问题是我不确定用户是否使用相同的字母映射了驱动器。
有没有办法为宏设置它来代替使用网络路径?
答案 0 :(得分:1)
您可以使用Dir()
测试文件夹是否存在:
Sub Get_Data()
If Dir("M:\", vbDirectory) <> vbNullString Then
'''Drive mapped
ChDrive "M:\"
Else
'''Drive not mapped
ChDir "\\netDrive\xxx$\yyy"
End If
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a file to import", _
FileFilter:="Excel Files *.xls (*.xls),")
If FileToOpen = False Then
MsgBox "No file specified.", vbExclamation, "Duh!!!"
Exit Sub
Else
Workbooks.Open FileName:=FileToOpen
End If
End Sub
答案 1 :(得分:1)
我找到了解决方案here。找到我用过的代码:
Private Declare Function SetCurrentDirectoryA Lib "kernel32" _
(ByVal lpPathName As String) As Long
Function SetUNCPath(sPath As String) As Long
Dim lReturn As Long
lReturn = SetCurrentDirectoryA(sPath)
SetUNCPath = lReturn
End Function
Sub Get_Data()
Dim sPath As String
sPath = "\\netDrive\xxx$\yyy"
If SetUNCPath(sPath) <> 0 Then
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a file to import", _
FileFilter:="Excel Files *.xls (*.xls),")
''
If FileToOpen = False Then
MsgBox "No file specified.", vbExclamation, "Duh!!!"
Exit Sub
Else
Workbooks.Open Filename:=FileToOpen
End If
Else
MsgBox "Error in setting the UNC path - " & sPath
End If
End Sub
答案 2 :(得分:0)
Set fldr = Application.FileDialog(msoFileDialogFilePicker)
您可以使用此选项将当前文件夹设置为出现打开对话框时显示的文件夹
答案 3 :(得分:0)
如果有帮助,可以通过以下方法打开网络中的文件:
Sub OpnRef()
Application.Workbooks.Open ("\\Server\Share\Shared Report Area\Reference Docs
\Reference1File.xlsx")
End Sub