Insert Directory File Listing Into Word

I wrote the following code to insert a list of the files in a directory, directly into Microsoft Word. The following code should work with any version of Word after 97, though it hasn't been tested on all of them. I use a modified version of the following code practically every day.

To install the code in word:

  1. Open up the Visual Basic Editor.
  2. Create a new module in Word. I would suggest placing this module in your Normal.dot file, so it can be used in any word document.
  3. Paste the code below into the module.
  4. Save the module.
Once you have the module installed, calling subroutine InsertDirContents will pop-up a "Browse For Folder" dialog box. Select the folder you want, and a listing of its files will appear in word.

For ease of use, you may wish to add a command button on one of Word's toolbars, calling the macro InsertDirContents.

Option Explicit Private Const BIF_RETURNONLYFSDIRS = 1 Private Const BIF_DONTGOBELOWDOMAIN = 2 Private Const MAX_PATH = 260 Private Declare Function SHBrowseForFolder Lib "shell32" _ (lpbi As BrowseInfo) As Long Private Declare Function SHGetPathFromIDList Lib "shell32" _ (ByVal pidList As Long, _ ByVal lpBuffer As String) As Long Private Declare Function lstrcat Lib "kernel32" Alias "lstrcatA" _ (ByVal lpString1 As String, ByVal _ lpString2 As String) As Long Private Type BrowseInfo hWndOwner As Long pIDLRoot As Long pszDisplayName As Long lpszTitle As Long ulFlags As Long lpfnCallback As Long lParam As Long iImage As Long End Type Public Function BrowseForFolder(Optional ByVal szTitle As String) As String 'Uses the WindowsAPI SHBrowseForFolder to browse to a folder Dim lpIDList As Long Dim sBuffer As String Dim tBrowseInfo As BrowseInfo With tBrowseInfo .lpszTitle = lstrcat(szTitle, "") .ulFlags = BIF_RETURNONLYFSDIRS End With lpIDList = SHBrowseForFolder(tBrowseInfo) If (lpIDList) Then sBuffer = Space(MAX_PATH) SHGetPathFromIDList lpIDList, sBuffer sBuffer = Left(sBuffer, InStr(sBuffer, vbNullChar) - 1) End If BrowseForFolder = sBuffer End Function Public Sub InsertDirContents() Dim FolderPath As String Dim TargetDoc As Word.Document Dim FileName As String Dim FileType As Integer FolderPath = BrowseForFolder("Select a directory.") If FolderPath <> "" Then 'Create a word document as a target if one is not already open If Application.Documents.Count < 1 Then Documents.Add ("Normal") Selection.Collapse (wdCollapseEnd) 'Select the type of files to insert into word. As set up, this 'does not include folders - adding vbDirectory to Filetype will add them FileType = vbNormal + vbReadOnly + vbHidden + vbSystem FileName = Dir(FolderPath & "\", FileType) Do While FileName <> "" With Selection .InsertAfter FileName .InsertParagraphAfter End With FileName = Dir Loop Selection.Collapse (wdCollapseEnd) End If End Sub

Created on ... April 10, 2004