Tuesday, October 2, 2012

VBA List all files in directory - Word


Sub List_All_Docs_in_Directory()

'______________________________________
'
'This VBA macro lists all files in a directory
'This quick macro works in Word
'______________________________________
'

Dim The_Directory_Path, The_File_Name, The_Path_To_List, All_Files
Dim The_Variable As String

The_Directory = "C:\"
All_Files = "*.*"

The_Path_To_List = The_Directory & All_Files
                              'Choose the directory where the files are
                              'You can also choose which type of file you want,
                              'for example, if you want only Word documents,
                              'use this: All_Files = "*.doc"
                   
If Len(The_Path_To_List) = 0 Then Exit Sub

The_Directory_Path = Dir(The_Path_To_List)
The_File_Name = The_Directory_Path

Do Until The_File_Name = ""
    If (The_File_Name <> "." Or The_File_Name <> "..") Then
     The_Variable = The_File_Name
      Selection.TypeText Text:=The_File_Name & vbNewLine
               'if you also want the date and time, add this:
               ' & vbTab & FileDateTime(The_Directory & The_File_Name) & vbNewLine
      The_File_Name = Dir
    End If
Loop

End Sub

No comments:

Post a Comment

You may comment or show me other VBA tricks, but don't rest assured I'll always reply because I only have 24 hours in a day's hard work, and only a few minutes a week to update this blog... I'll try my best though...