Mail sheets to address in cell A1 - keeping format - excel

Please can someone advise me on this issue. I have the below code from Ron de Bruin site to send multiple sheets to email addresses in cell A1.
However when the email is received it has changed the format of the times on the sheets i.e 16:00:00 changed to 0.666666667
can anyone see how it can be adapted to keep the 16:00:00?
Option Explicit
Sub Mail_Every_Worksheet()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim sh As Worksheet
Dim wb As Workbook
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim TempFilePath As String
Dim TempFileName As String
Dim OutApp As Object
Dim OutMail As Object
TempFilePath = Environ$("temp") & ""
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
FileExtStr = ".xlsm": FileFormatNum = 52
End If
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set OutApp = CreateObject("Outlook.Application")
For Each sh In ThisWorkbook.Worksheets
If sh.Range("A1").Value Like "?*#?*.?*" Then
sh.Copy
Set wb = ActiveWorkbook
'Change all cells in the worksheet to values
With wb.Sheets(1).UsedRange
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
End With
Application.CutCopyMode = False
TempFileName = "Sheet " & sh.Name & " of " _
& ThisWorkbook.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
Set OutMail = OutApp.CreateItem(0)
With wb
.SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
On Error Resume Next
With OutMail
.To = sh.Range("A1").Value
.CC = ""
.BCC = ""
.Subject = "TEST"
.Body = "Hi there"
.Attachments.Add wb.FullName
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
On Error GoTo 0
.Close savechanges:=False
End With
Set OutMail = Nothing
Kill TempFilePath & TempFileName & FileExtStr
End If
Next sh
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub

I got nerd sniped by your question and refactored your code.
Public Sub Mail_Every_Worksheet()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
Dim emailAddress As String
emailAddress = sh.Range("A1").Value2
If IsValidEmailAddress(emailAddress) Then
Dim tempFileName As String
tempFileName = "Sheet " & sh.Name & " of " & ThisWorkbook.Name & " " & Format$(Now, "dd-mmm-yy h-mm-ss")
Dim tempBook As Workbook
Set tempBook = CreateTempWorkbookFrom(sh, Environ$("temp"), tempFileName)
Dim tempBookFullPath As String
tempBookFullPath = tempBook.FullName
tempBook.Close
SendOutlookEmailTo emailAddress, vbNullString, vbNullString, "Subject", "Body", tempBookFullPath
Kill tempBookFullPath
End If
Next
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Private Function IsValidEmailAddress(ByVal value As String) As Boolean
IsValidEmailAddress = (value Like "?*#?*.?*")
End Function
Private Function CreateTempWorkbookFrom(ByVal copySheet As Worksheet, ByVal tempSavePath As String, ByVal tempFileName As String) As Workbook
If Right$(tempSavePath, 1) <> Application.PathSeparator Then
tempSavePath = tempSavePath & Application.PathSeparator
End If
copySheet.Copy
Set CreateTempWorkbookFrom = ActiveWorkbook
With CreateTempWorkbookFrom.Worksheets(1).UsedRange
'Change all cells in the worksheet to values
.Cells.Value2 = .Cells.Value2
End With
If Val(Application.Version) < 12 Then
CreateTempWorkbookFrom.SaveAs tempSavePath & tempFileName & ".xls", xlWorkbookNormal
Else
CreateTempWorkbookFrom.SaveAs tempSavePath & tempFileName & ".xlsm", xlOpenXMLWorkbookMacroEnabled
End If
End Function
Private Sub SendOutlookEmailTo(ByVal emailAddress As String, _
ByVal CC As String, _
ByVal BCC As String, _
ByVal Subject As String, _
ByVal Body As String, _
ParamArray attachments() As Variant)
On Error Resume Next
Dim mailItem As Object 'Outlook.mailItem 'Tools>References>Microsoft Outlook X.xx Object Library
Const OutlookMailItem As Long = 0
Set mailItem = CreateObject("Outlook.Application").CreateItem(OutlookMailItem) ' Outlook.Application.CreateItem(olMailItem)
With mailItem
.To = emailAddress
.CC = CC
.BCC = BCC
.Subject = Subject
.Body = Body
Dim attachment As Variant
For Each attachment In attachments
.attachments.Add attachment
Next
.Display
.Send
End With
On Error GoTo 0
End Sub

Related

Compiling condition across multiple worksheets to output 1 "solution". Also call out which worksheets(s) fit the condition

I am new to vba and struggling with trying to accomplish having a single overall email send out if any worksheet column L/M have a value below 1 and want it to call out which sheet (or sheets) had the value <1 in the email body or subject line. I have spent countless hours searching the web, but nothing so far has really worked for me. The MsgBox function is working fine, just having issues with compiling the results to 1 email naming which worksheet had the <1 value and 1 "solution" for the whole workbook, instead of having an email sent for every single worksheet that the conditions fit. Thank you in advance.
Option Explicit
Sub Main()
Dim sh As Worksheet, i As Long
For Each sh In ActiveWorkbook.Worksheets
With WorksheetFunction
If .CountIf(sh.Range("L3:L26"), "<1") > 0 Then
Call SendReminderMail1
Else
MsgBox "Rotations NOT needed for """ & sh.Name & """."
End If
If .CountIf(sh.Range("M3:M20"), "<1") > 0 Then
Call SendReminderMail2
Else
MsgBox "Functions are NOT needed for """ & sh.Name & """."
End If
End With
Next
End Sub
Sub SendReminderMail1()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim sh As Worksheet
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim OutApp As Object
Dim OutMail As Object
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set wb1 = ActiveWorkbook
TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))
wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
wb2.Worksheets(1).Range("A1").Value = "Copy created on " & Format(Date, "dd-mmm-yyyy")
wb2.Save
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "test#test.com"
.CC = ""
.BCC = ""
.Subject = "Rotations are due for """ & sh.Name & """."
.Body = "Hi there bud, ya need to take a good ole look at this here document. You've been slackin', let's fix that."
.Attachments.Add wb2.FullName
.Display 'or use .Display
End With
On Error GoTo 0
wb2.Close savechanges:=False
Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox "Your Automated Email for Rotations was successfully ran at " & TimeValue(Now), vbInformation
End Sub
Sub SendReminderMail2()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim sh As Worksheet
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim OutApp As Object
Dim OutMail As Object
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set wb1 = ActiveWorkbook
TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))
wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
wb2.Worksheets(1).Range("A1").Value = "Copy created on " & Format(Date, "dd-mmm-yyyy")
wb2.Save
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "test#test.com"
.CC = ""
.BCC = ""
.Subject = "Functions are due for """ & sh.Name & """."""
.Body = "Hi there bud, ya need to take a good ole look at this here document."
.Attachments.Add wb2.FullName
.Display 'or use .Display
End With
On Error GoTo 0
wb2.Close savechanges:=False
Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox "Your Automated Email for Functions was successfully ran at " & TimeValue(Now), vbInformation
End Sub
Try something like this:
Sub Main()
Dim sh As Worksheet, i As Long, shtsRotations As String
Dim shtsFunctions As String, shtsOK As String
For Each sh In ActiveWorkbook.Worksheets
If Application.CountIf(sh.Range("L3:L26"), "<1") > 0 Then
shtsRotations = shtsRotations & vbLf & sh.Name
Else
shtsOK = shtsOK & vbLf & sh.Name & " (Rotations)"
End If
If Application.CountIf(sh.Range("M3:M20"), "<1") > 0 Then
shtsFunctions = shtsFunctions & vbLf & sh.Name
Else
shtsOK = shtsOK & vbLf & sh.Name & " (Functions)"
End If
Next sh
If Len(shtsRotations) > 0 Then
SendReminderMail "test#test.com", "Rotations are due for worksheet(s).", _
"Hi there bud, ya need to take a good ole look at this here document." & _
"Check sheets: " & shtsRotations & vbLf & _
"You've been slackin', let's fix that."
End If
If Len(shtsFunctions) > 0 Then
SendReminderMail "test#test.com", "Functions are due for worksheet(s).", _
"Hi there bud, ya need to take a good ole look at this here document." & _
"Check sheets: " & shtsFunctions & vbLf & _
"You've been slackin', let's fix that."
End If
If Len(shtsOK) > 0 Then
MsgBox "These sheets are OK: " & vbLf & shtsOK, vbInformation
End If
End Sub
Sub SendReminderMail(sTo As String, sSubject As String, sBody As String)
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim sh As Worksheet
Dim TempFilePath As String, TempFileName As String
Dim FileExtStr As String, OutApp As Object, OutMail As Object
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set wb1 = ActiveWorkbook
TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))
wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
wb2.Worksheets(1).Range("A1").Value = "Copy created on " & Format(Date, "dd-mmm-yyyy")
wb2.Save
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "test#test.com"
.CC = ""
.BCC = ""
.Subject = sSubject
.Body = sBody
.Attachments.Add wb2.FullName
.Display
End With
On Error GoTo 0
wb2.Close savechanges:=False
Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox "Your Automated Email was successfully ran at " & TimeValue(Now), vbInformation
End Sub
You can reduce your code size by creating a single sub to send a mail, and passing in the variable parts.

How can I get an Excel generated email to auto fill the subject with a cell value?

I am trying to get Excel to auto fill the subject line with a specific cell value when an email is generated.
Currently My code for the email process is:
Sub EmailStage1Answers()
'
' EmailStage1Answers Macro
Dim wb1 As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim OutApp As Object
Dim OutMail As Object
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set wb1 = ActiveWorkbook
TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))
wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "EMAIL HIDDEN FOR POSTING"
.CC = ""
.BCC = ""
.Subject = "Assessment Form, Stage 1 ***INSERT PROJECT NAME***"
.Body = "Please see the latest copy of the Assessment Form attached. NOTE: Please ensure you have inserted the project name above."
.Attachments.Add TempFilePath & TempFileName & FileExtStr
.display
End With
On Error GoTo 0
Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
The workbook has a total of 19 pages and I want to populate the subject from a specific cell on the third page.
Can anyone advise?

Personal Macro not functioning: Selecting range and pasting into body of Outlook email

While piecing together this code, I was able to get it function properly. Thinking I was done, I submitted it to someone who tried to add it as a personal macro and that was when we realized it didn't work the same. To verify, I added it as a personal macro on my own computer and it still didn't work.
I have blindly tried a handful of code additions such as ChartObject.Activate after ThisWorkbook.Activate but have not had success.
Sub RangeToEmailBody()
Dim TempFilePath As String
Dim xOutApp As Object
Dim xOutMail As Object
Dim xHTMLBody As String
Dim xRg As Range
On Error Resume Next
Set xRg = Application.InputBox(prompt:="Please select the data range:", Type:=8)
If xRg Is Nothing Then Exit Sub
With Application
.Calculation = xlManual
.ScreenUpdating = False
.EnableEvents = False
End With
Set xOutApp = CreateObject("outlook.application")
Set xOutMail = xOutApp.CreateItem(olMailItem)
Call createJpg(ActiveSheet.Name, xRg.Address, "DashboardFile")
TempFilePath = Environ$("temp") & "\"
xHTMLBody = "<span LANG=EN>" _
& "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
& "<img src='cid:DashboardFile.jpg'>"
With xOutMail
.Subject = ""
.HTMLBody = xHTMLBody
.Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue
.To = " "
.Cc = " "
.Display
End With
End Sub
Sub createJpg(SheetName As String, xRgAddrss As String, nameFile As String)
Dim xRgPic As Range
ThisWorkbook.Activate
Worksheets(SheetName).Activate
Set xRgPic = ThisWorkbook.Worksheets(SheetName).Range(xRgAddrss)
xRgPic.CopyPicture
With ThisWorkbook.Worksheets(SheetName).ChartObjects.Add(xRgPic.Left, xRgPic.Top, xRgPic.Width, xRgPic.Height)
.Activate
.Chart.Paste
.Chart.Export Environ$("temp") & "\" & nameFile & ".jpg", "JPG"
End With
Worksheets(SheetName).ChartObjects(Worksheets(SheetName).ChartObjects.Count).Delete
Set xRgPic = Nothing
End Sub
I would expect the selected range to show up in the body of the email but as a personal macro, there is no content inside the "picture".
This is a guess at the problem. If you're adding this in a personal macro, ThisWorkbook refers to the personal workbook. I'm guessing your source range is in a different workbook entirely.
To simplify, I'd do something like this, using a temporary new workbook:
Sub createJpg(rng As Range, nameFile As String)
Dim tempChartObj As ChartObject
Dim tempWb As Workbook
Set tempWb = Workbooks.Add
Set tempChartObj = tempWb.Sheets(1).ChartObjects.Add(rng.Left, rng.Top, rng.Width, rng.Height)
rng.CopyPicture
With tempChartObj
.Activate
.Chart.Paste
.Chart.Export Environ$("temp") & "\" & nameFile & ".jpg", "JPG"
End With
tempWb.Close SaveChanges:=False
End Sub
Then call it like this (note that Call is unnecessary):
createJpg xRg, "DashboardFile"

Mail every worksheet with Different signature use excel vba

i need your help
the below code work to send email for the sheets my question ?
how i can change the signature automated ? i have the name of the signature in the excel file lets call it (b2) .
its possible to make it ?
Note : i use excel 365 and widows 10
Sub Mail_Every_Worksheet()
Dim sh As Worksheet
Dim wb As Workbook
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim TempFilePath As String
Dim TempFileName As String
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
TempFilePath = Environ$("temp") & "\"
'You use Excel 2007-2016
FileExtStr = ".xls": FileFormatNum = 52
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set OutApp = CreateObject("Outlook.Application")
For Each sh In ThisWorkbook.Worksheets
If sh.Range("A2").Value Like "?*#?*.?*" Then
sh.Copy
Set wb = ActiveWorkbook
TempFileName = sh.Name
Set OutMail = OutApp.CreateItem(0)
With wb
.SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
On Error Resume Next
With OutMail
.Attachments.Add wb.FullName
.Display
strbody = "HI sony "
.to = sh.Range("A2").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = "HI sony " & "<br>" & .HTMLBody
.Send
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
End With
On Error GoTo 0
.Close savechanges:=False
End With
Set OutMail = Nothing
Kill TempFilePath & TempFileName & FileExtStr
End If
Next sh
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
If you just want to add the default signature then display the email before sending it:
.Display
.HTMLBody = strbody & "<br>" & .HTMLBody
.Send
If, however, you want to use a specific signature file then you will need to read that file:
SigString = Environ("appdata") & "\Microsoft\Signatures\B2.htm"
If Dir(SigString) = "" Then
OutSignature = ""
Else
Dim fso As Object
Dim sf As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set sf = fso.GetFile(SigString).OpenAsTextStream(1, -2)
OutSignature = sf.readall
sf.Close
End If
.HTMLBody = strbody & "<br>" & OutSignature
.Send
I use Excel 2013 though this answer should not be restricted to that version.

Excel Send Emails Based on Worksheet Names

I made a macro that splits a main worksheet into different tabs and renames the tabs. I want to email the tabs to different people, by matching the tab name to a list containing email addresses.
What I have right now is this:
Sub Split_To_Workbook_and_Email_with_Body()
'Working in 2013/2016
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim sh As Worksheet
Dim DateString As String
Dim FolderName As String
Dim myOutlook As Object
Dim myMailItem As Object
Dim mySubject As String
Dim myto As String
Dim myPath As String
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
'Prompt for Email Subject
Set otlApp = CreateObject("Outlook.Application")
'mySubject = InputBox("Subject for Email")'this shows a dialog where you can enter the email subject (right now it is hard coded)
'myto = Application.VLOOKUP(SheetId, Sheet1!A3:B48, 2, FALSE)
'myto = Application.VLookup(SheetId, Sheet1!A3:B48, 2, range_lookup)
'Copy every sheet from the workbook with this macro
Set Sourcewb = ActiveWorkbook
'Create new folder to save the new files in
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = "Z:\user\report" & Sourcewb.Name & " " & DateString
MkDir FolderName
'Copy every visible sheet to a new workbook
For Each sh In Sourcewb.Worksheets
'If the sheet is visible then copy it to a new workbook
If sh.Visible = -1 Then
sh.Copy
'Set Destwb to the new workbook
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
If Sourcewb.Name = .Name Then
MsgBox "Your answer is NO in the security dialog"
GoTo GoToNextSheet
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End If
End With
'Change all cells in the worksheet to values if you want
If Destwb.Sheets(1).ProtectContents = False Then
With Destwb.Sheets(1).UsedRange
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells(1).Select
End With
Application.CutCopyMode = False
End If
'Save the new workbook, email it, and close it
Set otlNewMail = otlApp.CreateItem(olMailItem)
With Destwb
.SaveAs FolderName _
& "\" & Destwb.Sheets(1).Name & FileExtStr, _
FileFormat:=FileFormatNum
End With
myPath = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
idkfile = "C:\Users\UniaHa\Desktop\Testing.txt"
With Destwb
.Close False
End With
With otlNewMail
'.Subject = mySubject
.to = test#test.ca
.Subject = "Diversion Report"
.Body = "Dear customer," & vbNewLine & vbNewLine & _
"This is your report please..... blah blah" & _
vbNewLine & vbNewLine & "Regards," & vbNewLine & vbNewLine & "Sender Name"
.Attachments.Add myPath
.Attachments.Add idkfile
.Display
End With
Set otlNewMail = Nothing
End If
GoToNextSheet:
Next sh
MsgBox "You can find the files in " & FolderName
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
End With
End Sub
For your vlookup, you can try something like:
On Error Resume Next
for each sht in activeworkbook.worksheets
err.clear
sEmailTo = Application.worksheetfunction.VLOOKUP(sh.name, Sheet1!A3:B48, 2, FALSE)
if err<>0 and semailto like "*#*" Then
'send your email
end if
next sht
On Error goto 0

Resources