Consulting

Results 1 to 2 of 2

Thread: How to attach most recent file in a folder to an email

  1. #1
    VBAX Newbie
    Joined
    Apr 2015
    Posts
    1
    Location

    Angry How to attach most recent file in a folder to an email

    I am looking to attach the most recent .pdf file located at Z:\ANEECE
    I have looked on forums but not found anything that worked.

    Below is the basic setup for the rest of the email. I am NEW to this any help would be appreciated.
    *edit I cannot post urls yet.. so i cant post my sample here that I am using

  2. #2
    The following macro should add the latest PDF file in the named folder:
    Option Explicit
    
    Sub AttachPDF()
    Dim olMsg As MailItem
    Dim strFilename As String
    Const strPath As String = "Z:\ANEECE\"
        On Error GoTo ErrHandler
        If TypeName(ActiveWindow) = "Inspector" Then
            If ActiveInspector.IsWordMail And ActiveInspector.EditorType = olEditorWord Then
                Set olMsg = ActiveInspector.CurrentItem
                strFilename = LatestPDFFile(strPath)
                olMsg.Attachments.Add strPath & strFilename
            End If
        End If
    lbl_Exit:
        Set olMsg = Nothing
        Exit Sub
    ErrHandler:
        Beep
        Resume lbl_Exit
    End Sub
    
    
    Function LatestPDFFile(strPath As String) As String
    Dim FileName As String
    Dim MostRecentFile As String
    Dim MostRecentDate As Date
        If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
        FileName = Dir(strPath & "*.pdf", 0)
        If FileName <> "" Then
            MostRecentFile = FileName
            MostRecentDate = FileDateTime(strPath & FileName)
            Do While FileName <> ""
                If FileDateTime(strPath & FileName) > MostRecentDate Then
                    MostRecentFile = FileName
                    MostRecentDate = FileDateTime(strPath & FileName)
                End If
                FileName = Dir
            Loop
        End If
        LatestPDFFile = MostRecentFile
    lbl_Exit:
        Exit Function
    End Function
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •