Microsoft Word Recent Files VBA (Visual Basic for Applications)

Microsoft Word Recent Files VBA (Visual Basic for Applications)

RecentFile

Object helps identifying recently used (i.e. Open) files in Word Application. Microsoft Word object model offers RecentFiles collection which contains all the recent files. A file can be accessed through an index (a positive integer value). The Recent Files are displayed at the bottom of the File menu. as shown below:

Count property

Public Sub GetCountOfRecentFiles()
    MsgBox "You have totoal recently opened files : " & RecentFiles.Count
End Sub

Output

Name property

Public Sub GetNameOfRecentFiles()
    'Declare a local variable for recentfile
    Dim oRecentFile As RecentFile
    
    'Iterate each recent file and print name
    For Each oRecentFile In RecentFiles
        Debug.Print oRecentFile.Name
    Next oRecentFile
    
    'Memory cleanup
    Set oRecentFile = Nothing
End Sub

Output

test.docm
VBAOVERALL.docm
VBAOVERALL_Addin.dotm

Add method

Public Sub AddRecentFile()
    'Declare document object
    Dim oDocument As Document
    'Bind reference
    Set oDocument = ActiveDocument
    
    'Check if document is saved
    If oDocument.Saved = True Then
        'declare local variable to get the name of document
        Dim oDocPath As String
        'Obtain full path
        oDocPath = oDocument.FullName
        'Add to recent file collection
        RecentFiles.Add Document:=oDocPath, ReadOnly:=True
    End If
    
    'Memory clean up
    Set oDocument = Nothing
End Sub

Open method

Public Sub OpenRecentFile()
    'Declare document object
    Dim oDocument As Document
    
    'Declare a local variable for recentfile
    Dim oRecentFile As RecentFile
    
    'Iterate each recent file and print name
    For Each oRecentFile In RecentFiles
        'Open file where file name is test.docx
        If oRecentFile.Name = "test.docx" Then
            Set oDocument = oRecentFile.Open
            Exit For
        End If
    Next oRecentFile
    
    'Memory cleanup
    Set oRecentFile = Nothing
    Set oDocument = Nothing
End Sub

Delete method

Public Sub DeleteRecentFile()
    'Declare document object
    Dim oDocument As Document
    
    'Declare a local variable for recentfile
    Dim oRecentFile As RecentFile
    
    'Iterate each recent file and print name
    For Each oRecentFile In RecentFiles
        'Open file where file name is test.docx
        If oRecentFile.Name = "test.docx" Then
            oRecentFile.Delete
            Exit For
        End If
    Next oRecentFile
    
    'Memory cleanup
    Set oRecentFile = Nothing
    Set oDocument = Nothing
End Sub

Next >> Conditional Formatting in Word Document VBA code

Leave a Reply

Your email address will not be published. Required fields are marked *