Visual Basic 6 function "OpenFile"

Go back

Below you'll find the source for the Visual Basic 6 function OpenFile.

Attribute VB_Name = "modOpenFile"
' This function is downloaded from:
' You may freely distribute this file but please leave all comments, including this one, in it.
' @Author Stefan Thoolen <>

Private Declare Function CommDlgExtendedError Lib "comdlg32.dll" () As Long

Private Declare Function GetOpenFileNameA Lib "comdlg32.dll" (pOpenfilename As OPENFILENAME) As Long

Private Const OFN_HIDEREADONLY = &H4

' See also:
        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

' Displays an Open File dialog box
' @param    Long    hwnd        The Window Handler of it's caller
' @param    String  filter      A file filter (ex.: "Textfiles|*.txt|All files (*.*)|*.*")
' @param    String  title       The title of the dialog
' @param    String  path        The path to start in
' @return   String              The full path of a filename
' @author   Stefan Thoolen <>
Public Function OpenFile(ByVal hwnd As Long, Optional ByVal filter As String, Optional ByVal title As String, Optional ByVal path As String) As String
    ' Default values
    If filter = "" Then filter = "Images (*.gif;*.jpg;*.jpeg;*.png)|*.gif;*.jpg;*.jpeg;*.png|HTML (*.htm;*.html)|*.htm;*.html|All files (*.*)|*.*"
    If path = "" Then path = Chr(0)
    ' Prepairs the dialog
    With ofn
        .flags = OFN_HIDEREADONLY
        .hwndOwner = hwnd
        .lpstrFilter = Replace(filter, "|", Chr(0)) & Chr(0) & Chr(0)
        .lpstrTitle = title
        .lpstrInitialDir = path
        .lpstrFile = String(260, 0)
        .nMaxFile = Len(.lpstrFile)
        .lStructSize = Len(ofn)
    End With
    ' Displays the dialog
    If GetOpenFileNameA(ofn) = 0 Then ' 0 = Returned false
        Dim l As Long
        l = CommDlgExtendedError()
        If l = 0 Then Exit Function ' Cancelled
        MsgBox "CommonDialog Error: CDERR_" & LTrim(Str(l))
        Exit Function
    End If
    OpenFile = Left(ofn.lpstrFile, InStr(ofn.lpstrFile, Chr(0)) - 1)
End Function