Thursday, April 21, 2011

VB function to invoke dialog box for file selectoin

Small piece of code but really handy for file selections. Important, make sure that the Microsoft Office xx.x Object Library is checked, otherwise the Dialog object will not be recognized:
Function FindTxtFile(strFNme As String, strSearchPath As String, strTitle As String) As String
 Dim myDialog As FileDialog
 Dim vrtSelectedItem As Variant
Set myDialog = Application.FileDialog(msoFileDialogOpen)
With myDialog
    .AllowMultiSelect = False
    .Filters.Add "Text", "*.txt", 1
    .Title = strTitle
'    Debug.Print Right(strSearchPath, Len(strSearchPath) - 10)
    .InitialFileName = strSearchPath & strFNme
    If .Show = -1 Then
        For Each vrtSelectedItem In .SelectedItems
            FindTxtFile = Trim(vrtSelectedItem)
        Next vrtSelectedItem
    End If
   Set myDialog = Nothing
End With
End Function