Filepicker VBA to select file and store the file name not working

断了今生、忘了曾经 提交于 2021-02-05 09:55:08

问题


I am trying to run the following in order to get the file name that the user selects. The file is an .mdf file that is attached previously to an SQL server. But when I run it, a window comes out and says I don't have permission to open the file. I know it is because it is being used in SQL, because if I don't attach it in the SQL server it runs without a problem. The thing is that I need the mdf in SQL before running the vba code and I just need the file name. Is there a way to store the file name without "opening" it?

Function GetDB() As String

Dim db As Office.FileDialog
Dim fileName As String
Set db = Application.FileDialog(msoFileDialogFilePicker)
With db
    .Title = "Select a Database"
    .AllowMultiSelect = False
    .InitialFileName = Application.DefaultFilePath
      Application.DisplayAlerts = False
    If .Show = True Then
    fileName = Mid(.SelectedItems(1), InStrRev(.SelectedItems(1), "\") + 1)
        End If
    End With
End Function

回答1:


replace

sItem = .SelectedItems(1)

with:

GetDB = .SelectedItems(1)



回答2:


I ended up setting and ADODB Connection to get the databases directly from the server without having the "The file is in use" issue.



来源:https://stackoverflow.com/questions/51828080/filepicker-vba-to-select-file-and-store-the-file-name-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!