Hi there!
Does somebody know how I can open the "Open file" dialog box with VBA?
What I want to do is to select a file on the network and save the path in a variable in VBA. Is this possible? And if yes, how can I do that?
Many thanks,
Roberto
Hello,
Paste the code that follows in to a new module and use the following syntax to run the function
GetFileBox(Initial Path, Dialog Box Title, Filter) e.g Getfilebox("c:\","Open File","*.mdb".
------Code Starts---------
Option Compare Database
Option Explicit
Public lngRowNumber As Long 'Stores the row number where the data error has occured
Public lngRecordCount As Long 'Stores the total record count
'
'Module to Open a Windows File Dialog Box.
'
'Function uses "comdlg32.dll" and therefore will work with Access '97 and 2000
'
'Functions Included :
'
'OpenAccessFile
'SaveAccessFile
'OpenAnyFile
'SaveAnyFile
'OpenTextFile 'Text File includes option to open/save CSV file.
'SaveTextFile
'
'Just call the function with optional initial directory(Default = C:\)
'Selected Filepath and Name will be returned.
'
'Origin of API code unknown.
Public Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
Public Declare Function GetSaveFileName Lib "comdlg32.dll" Alias "GetSaveFileNameA" (pOpenfilename As OPENFILENAME) As Long
Public Type OPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
lpstrFile As String
nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
Function GetFilebox(strInitialD As String, strTitle As String, strFilter As String) As String
On Error GoTo ERR_GetFilebox
Dim OpenFile As OPENFILENAME
Dim lReturn As Long
Dim sFilter As String
OpenFile.lStructSize = Len(OpenFile)
OpenFile.hwndOwner = Screen.ActiveForm.Hwnd
OpenFile.lpstrFilter = strFilter
OpenFile.nFilterIndex = 1
OpenFile.lpstrFile = String(257, 0)
OpenFile.nMaxFile = Len(OpenFile.lpstrFile) - 1
OpenFile.lpstrFileTitle = OpenFile.lpstrFile
OpenFile.nMaxFileTitle = OpenFile.nMaxFile
OpenFile.lpstrInitialDir = strInitialD
OpenFile.lpstrTitle = strTitle
OpenFile.flags = 0
lReturn = GetOpenFileName(OpenFile)
If lReturn = 0 Then
GetFilebox = ""
Else
GetFilebox = Trim(OpenFile.lpstrFile)
End If
Exit_GetFilebox:
Exit Function
ERR_GetFilebox:
Select Case Err.Number
Case 2475
OpenFile.hwndOwner = 0
Resume Next
Case Else
MsgBox "Error : " & Err.Number & vbCr & vbCr & Err.Description
End Select
Resume Exit_GetFilebox
End Function
Make things as simple as possible — but no simpler.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.