Search code examples
sql-servervbafiledialogfilepicker

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


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

Solution

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