2017-02-21 32 views
0

我想在打开的文件对话框中指定一个网络目录,但我遇到了一些问题。我试图使用的代码如下:Excel宏在网络目录打开文件

Sub Get_Data() 
    'ChDrive "M:\" 
ChDir "\\netDrive\xxx$\yyy" 
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 

的驱动器映射为M,所以如果我将以下代码它的工作原理:

ChDrive "M:\" 
ChDir "\yyy" 

的问题是,我不不知道用户是否用相同的字母映射了驱动器。

有没有一种方法可以将宏设置为使用网络路径?

+1

是的,你可以通过它的[UNC名称(https://en.wikipedia.org/wiki/Path_(计算)#Uniform_Naming_Convention)打开工作簿。 –

+0

UNC是\\ netDrive \ xxx $,但添加ChDrive“\\ netDrive \ xxx $'&ChDir”\ yyy“似乎没有工作 – Selrac

+0

我的公司使用网络驱动器,我只是使用”FollowHyperlink路径)“命令,这并不理想,但它可能是一个快速的解决方法。 –

回答

0

如果与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 
0

设置FLDR = Application.FileDialog(msoFileDialogFilePicker)

您可以使用它来设置当前文件夹出现在文件夹打开对话框出现

+0

这会打开与'我的文档'文件夹的对话框 – Selrac

0

我找到了解决方案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