Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Attach file to email

0
I have created an action register and i want to email to client as either a .pdf or .xlsx. I can write separate macros for both no issue and it works   What i want to do is write a macro that give you a choice attach as either .pdf or .xlsx using wild card   msgbox comes up click yes for .xlsx or no for .pdf   the PDF or XLSX file will be created and saved to the same folder each time and once the file is attached the file will be deleted - Kill file name   I have written the code for the msgbox choice - No problem   Create the PDF no problem and saves to the correct folder   when i go to attach to the email, the variable has the correct file name when you hover over but will not attach   Code   Sub mainmacro()   Dim response As VbMsgBoxResult   response = MsgBox("Please choose an action:" & vbNewLine & _                  "Yes - Run Macro One" & vbNewLine & _                  "No - Run Macro Two" & vbNewLine & _                  "Cancel - Exit", _                  vbYesNoCancel + vbQuestion, _                  "Action Required")                   Select Case response     Case vbYes         Call macro_one     Case vbNo         Call macro_two     Case vbCancel         macro_three End Select End Sub   Private Sub macro_two() '************************************************************************************************** ' This macro creates the .PDF file of the workbook ' Hides rows 3 to 5 ' It creates an array of the required 3 sheets ' Unhides rows 3 to 5 ' Calls the email macro and attaches the file to the email '*************************************************************************************************** ' New file variables. Dim wsToPrint As Worksheet ' This will hold the worksheet that we export as a PDF. Dim newFilename As String ' This will hold the full path, name and extension of the file we create.   ' Create a name for the new file so it can be saved.   newFilename = Dir("C:\Test\Export\*") Set wsToPrint = Worksheets("Stores") wsToPrint.Select   wsToPrint.Cells(1, 1).Select   ' Save PDF of The Worksheet    wsToPrint.ExportAsFixedFormat _         Type:=xlTypePDF, _         Filename:=newFilename, _         Quality:=xlQualityStandard, _         IgnorePrintAreas:=True, _         OpenAfterPublish:=False   MsgBox "PDF created"   Call macro_three   End Sub   Private Sub macro_three() '************************************************************************************************** ' This macro creates the email ' attaches the .xlsx or the PDF ' It then kills the filename '***************************************************************************************************     ' Email Section     Dim outlookApp As Object     Dim emailItem As Object     Dim emailSubject As String     Dim emailBody As String       Dim newFilename As String     newFilename = Dir("C:\Test\Export\*")         ' Get a reference to the Outlook Application Object.     Set outlookApp = CreateObject("Outlook.Application")         ' Create the Email Object Item     Set emailItem = outlookApp.CreateItem(0)         ' Setup values for the email.     emailSubject = "Subject line for the email."     emailBody = "The message for the email." & vbNewLine & _                 "Here is a second line." & vbNewLine & vbNewLine & _                 "And another line: " & vbTab & " with a tab."                     ' Build the Email     With emailItem         .To = "email@example.com"         .CC = ""         .BCC = ""         .Subject = emailSubject         .Body = emailBody     End With         ' Add attachments     emailItem.Attachments.Add newFilename When you hover over the variable it shows the correct filename, but fails to attach it to the email.         ' Send the email.     emailItem.Display ' .Display or .Send                ' Delete the newly created file.       Kill newFilename   End Sub
Answer
Discuss

Discussion

Semaj

Please edit your orginal question and use the CODE button to make it easier to read (select a section of code then click that button). This iwill help us and others- I don't have much time currently and suspect nor does Willie.

Preferably also add an Excel file (so we don't need to recreate one to test any possible solutions).
John_Ru (rep: 6607) Dec 20, '24 at 4:07 am
yes, good idea.
semaj (rep: 10) Dec 20, '24 at 4:12 am
Thanks! If you do that soon, I may have chance to respond later today (my tiime)
John_Ru (rep: 6607) Dec 20, '24 at 4:17 am
John, it won't be tonight but maybe tomorrow, its ok if i have to wait. Thanks for helping much appreciated
semaj (rep: 10) Dec 20, '24 at 5:12 am
Okay. I think it's just a problem with the filename being inadequate. Did you read my other Answer (on codename use)?
John_Ru (rep: 6607) Dec 20, '24 at 6:05 am
Yes I did worked perfectly
semaj (rep: 10) Dec 23, '24 at 7:06 am
Add to Discussion

Answers

0
Selected Answer

Hi again Semaj

Your question currently includes the wording of your code (but unformatted and so confusing) and does not contain your routine macro_one - please edit to correct.

However the problem arises with your use of the Dir function and the variable newFilename.

If you have a folder C:\Test\Export\ and it contains no files say, the line with an * wildcard (e.g. in macro_two):

newFilename = Dir("C:\Test\Export\*")

returns nothing.

If there are files in that folder, it would return the name of the first file it finds e.g. "ABC.xlsx" (if that is the first file alphabetically).

The problem is that your line:

emailItem.Attachments.Add newFilename

gives Outlook the string "ABC.xlsx" (which it can't find and so fails), rather than the necessary full path to the file e.g. it would need ."C:\Test\Export\ABC.xlsx".

That could be corrected e.g. using:

' Add attachments
If Dir("C:\Test\Export\" & newFilename) <> vbNullString Then
    emailItem.Attachments.Add "C:\Test\Export" & newFilename
End If 

but there are further problems:

  1. the line
    newFilename = Dir("C:\Test\Export\*")
    might return the name of a pdf file when you are trying to send an Excel file (and vice versa)
  2. at the end of macro_three, the line 
    Kill newFilename
      attempts to remove and existing file (and eventually that folder will contain no files) but it doesn't have the full path so would fail

I suggest you instead create a new (dated) file name which suits the file you want to export e.g for pdf in macro_two:

newFilename = "C:\Test\Export\" & "Report for " & Format(Date, "dd mmm yyyy") & ".pdf"

which would produce the full path C:\Test\Export\Report for 21 Dec 2024.pdf: which would add correctly (and could be deleted too) using your existing code.

You would need to change the ending for .xlxs files.

Hope this fixes your problem and you can select this Answer (but please don't forget to tidy up your question to help others).

Discuss

Discussion

@John,
Once again you have gone above and beyond. Semaj is now asking for more help without having selected your previous answer or provide feedback. Hopefully semaj will recognise and appreciate your generousity. Hopefully this poster will realize how lucky they are.
Cheers
WillieD24 (rep: 657) Dec 21, '24 at 1:42 pm
@Willie - thanks. It is the season of good will so in fairness to Semaj, he has selected other Answers (hence his Reputation points) and - in a Discussion yesterday - hinted that he might not respond over the weekend. I'm still hopeful of a meaningful response. 
John_Ru (rep: 6607) Dec 21, '24 at 2:54 pm
Hi Team, been reading through the responses, thank John, the above gave me a lot to think about and to be honest a day a way from this and reading the responses, i came up with using a Global variable, then clearing after each use. I can now save .PDF and .XLSX files in the same folder. only one at a time, but that is what i was after.
semaj (rep: 10) Dec 23, '24 at 6:51 am
[Const START_ROW As Long = 3 Const END_ROW As Long = 5 Public filePath As String - This is the new Public Variable
The 2 constants are for rows on each sheet i need to hide
semaj (rep: 10) Dec 23, '24 at 6:52 am
 Worksheets(Array(wsDashboard.Name, wsActionReg.Name)).Copy
.
I also used your idea for the codeName.name. This works perfectly thank you
semaj (rep: 10) Dec 23, '24 at 6:56 am
 Set wbNew = ActiveWorkbook
    'Define the file path and name
    newFilename = strFolderName & "\MultiSet Action Register " & Format(Date, "yyyy-mm-dd") & ".xlsx"
    'Save new workbook (wbNew)
    wbNew.SaveAs _
        Filename:=newFilename, _
        FileFormat:=51
    'Assign the file path to the global variable
    filePath = newFilename
    'Close the new workbook
    wbNew.Close False

This is where i have the new Gloabal variable
semaj (rep: 10) Dec 23, '24 at 6:57 am
.Attachments.Add filePath
        .Display 'Use .Send to send automatically
    End With
ExitSub:
    'Cleanup
    Set OutMail = Nothing
    Set OutApp = Nothing
    'Delete temp file
    If filePath = "" Then Exit Sub
    'Reset the global variable
    Kill filePath
    'Clear Gloabal Variable
    filePath = ""
    Exit Sub

this code shows the Global variable being used, and the Kill command and where i clear the Global variable filePath
semaj (rep: 10) Dec 23, '24 at 6:58 am
I appreciate the time you put into this for me, as i said earlier mades me think about the solution and how to fix some other parts of the code. Let me know if you want to see the finished produnt. Happy to share.
semaj (rep: 10) Dec 23, '24 at 7:00 am
Thanks for selecting my Answer, Semaj. I'm pleased that my Answer prompted further thought from you and that you have developed a neater solution to suit your needs. 

Thanks for offering your finished file for review but I'll be busy on family holiday matters for the next week or so. 
John_Ru (rep: 6607) Dec 23, '24 at 10:54 am
Merry Xmas and happy new year enjoy your time with your family, and thanks for all your help this year.
semaj (rep: 10) Dec 23, '24 at 10:03 pm
Thanks Senaj and the same to you : -) 
John_Ru (rep: 6607) Dec 24, '24 at 2:44 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login