ERLANDSEN DATA CONSULTING Excel & VBA Tips   Informasjon på norsk / Information in Norwegian

These pages are no longer updated and are only available for archive purposes.

Click here to visit the pages with updated information.

Select file- or folder names in Word

Word has not got the method GetOpenFileName that can be used to let a user select a file name or a folder. You can use the user defined function below:

Function WordApplicationGetOpenFileName(FileFilter As String, _
    ReturnPath As Boolean, ReturnFile As Boolean) As String
' returns the folder and/or filename to a single user selected file
Dim strFileName As String, strPathName As String
    If Not ReturnPath And Not ReturnFile Then Exit Function
       If FileFilter = "" Then FileFilter = "*.*"
    With Application.Dialogs(wdDialogFileOpen)
        .Name = FileFilter
        On Error GoTo MultipleFilesSelected
        If .Display = -1 Then
            strFileName = .Name
        End If
        On Error GoTo 0
    End With
    On Error GoTo 0
    ' remove any "-characters
    If InStr(1, strFileName, " ", vbTextCompare) > 0 Then
        strFileName = Mid$(strFileName, 2, Len(strFileName) - 2)
    End If
    If ReturnPath Then
        strPathName = CurDir & Application.PathSeparator
    Else
        strPathName = ""
    End If
    If Not ReturnFile Then strFileName = ""
    WordApplicationGetOpenFileName = strPathName & strFileName
MultipleFilesSelected:
End Function

Use the function like this to return a complete folder and file name:
FullFileName = WordApplicationGetOpenFileName("*.doc", True, True)

Use the function like this to return the file name only:
FileNameOnly = WordApplicationGetOpenFileName("*.doc", False, True)

Use the function like this to return the folder name only:
FolderNameOnly = WordApplicationGetOpenFileName("*.*", True, False)

 

Document last updated 2000-02-04 12:49:08      Printerfriendly version

User comments:
Ole P. from Norway wrote (2006-06-27 08:46:05 CET):
Re: Setting initial directory?
Do something like this before calling the function above:
ChDrive Left$(strInitialFolder, 1)
ChDir strInitialFolder
Nook Schreier from Barnesville, OH wrote (2006-06-26 18:50:19 CET):
Setting initial directory?
Thanks for this, it's a HUGE help, although I'm wondering if there is a way to specify what folder the dialog box opens into. If I had the macro for a very special purpose and always wanted to insert files from "C:\insert," is there a way to get the dialog box to open "C:\insert" every time this macro is run? Thanks. Oh, and since it's been 6 years since this page was written, I'm not really expecting an answer but hey, it's worth a try.

 

Erlandsen Data Consulting     http://www.erlandsendata.no/   
Excel & VBA Tips   Copyright ©1999-2024    Ole P. Erlandsen   All rights reserved
E-mail Contact Address