VBA Attachments.Add

Sarah Chen 21 Reputation points
2023-02-21T12:40:38.5833333+00:00

I have question on VBA code.

I want to write a code to send a mail with attachment.

But got below error message on .Attchments.Add

Problem is the file name is changing everyday, I cannot write a certain file path there..

in this case, how should I do?

Kindly advise.

Sub Send_Email()
'This code is early binding i.e in Tools >
'Reference >You have check "MICROSOFT OUTLOOK 14.0 OBJECT LIBRARY"

  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem
  Dim FileName As String
  Dim FilePath As String
  Dim Name As String


  Set OutlookApp = New Outlook.Application
  Set OutlookMail = OutlookApp.CreateItem(olMailItem)

  FilePath = "\\xxx\xxxx\xxxxx\xxxx\xxxxx\xxxxx\xxxxx\xxxxx\"
  Name = Range("I1").Value
  FileName = Dir(FilePath & Name & ".pdf")
   
  With OutlookMail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "Hi, <br> <br> Please see attached file! <br> <br> Thanks!"
    .To = ""
    .CC = ""
    .BCC = Range("I11").Value
    .Subject = Range("I1").Value
    
    .Display
       
End With  
End Sub

User's image

Microsoft 365 and Office | Development | Other
Microsoft 365 and Office | Excel | For business | Windows
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.