I have an Excel 2016 worksheet with a "Send Worksheet" button purposed to email the worksheet to all the designated recipients. When I run the following code (most of which came from another program and tweaked), I receive the following errors:
Runtime Error 429: ActiveX component can't create object.
at Set OutlookApp = CreateObject("Outlook.Application")
as well as
Runtime Error 91: Object variable or With block variable not set.
in the With block at .To = "email address".
Option Explicit
Private Sub cmdSendWorksheet_Click()
Dim xFile As String
Dim xFormat As Long
Dim Wb As Workbook
Dim Wb2 As Workbook
Dim FilePath As String
Dim FileName As String
Dim OutlookApp As Object
Dim OutlookMail As Object
'On Error Resume Next
Application.ScreenUpdating = False
Set Wb = Application.ActiveWorkbook
ActiveSheet.Copy
Set Wb2 = Application.ActiveWorkbook
Select Case Wb.FileFormat
Case xlOpenXMLWorkbook:
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
Case xlOpenXMLWorkbookMacroEnabled:
If Wb2.HasVBProject Then
xFile = ".xlsm"
xFormat = xlOpenXMLWorkbookMacroEnabled
Else
xFile = ".xlsm"
xFormat = xlOpenXMLWorkbook
End If
End Select
FilePath = Environ$("temp") & "\"
FileName = Wb.Name & Format(Now, "dd-mmm-yy h-mm-ss")
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
With OutlookMail
.To = "email address"
.CC = ""
.BCC = ""
.Subject = "Worksheet Attached"
.Body = "Please see attached worksheet"
.cmdSendWorksheet.Enabled = True
.Attachments.Add Wb2.FullName
.Send
End With
Wb2.Close
Kill FilePath & FileName & xFile
Set OutlookMail = Nothing
Set OutlookApp = Nothing
Application.ScreenUpdating = True
End Sub
this code should do the job you need. But you need to go in Tools / References and check the following reference :
Microsoft Scripting Runtime
Microsoft Outlook 14.0 Object Library
Private Sub cmdSendWorksheet_Click()
Dim Wb As Workbook
Dim FilePath As String
Dim FileName As String
Dim FileExtensionName As String
Dim FileFullPath As String
Dim OutlookApp As New Outlook.Application
Dim OutlookMail As Outlook.MailItem
Dim fso As New FileSystemObject
'On Error Resume Next
Application.ScreenUpdating = False
Set Wb = ThisWorkbook
FilePath = Environ$("temp") & "\"
FileName = fso.GetBaseName(Wb.Path & "\" & Wb.Name) & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtensionName = fso.GetExtensionName(Wb.Path & "\" & Wb.Name)
FileFullPath = FilePath & FileName & "." & FileExtensionName
fso.CopyFile Wb.Path & "\" & Wb.Name, FileFullPath
'Sending the email
Set OutlookMail = OutlookApp.CreateItem(olMailItem)
With OutlookMail
.To = "email address"
.CC = ""
.BCC = ""
.Subject = "Worksheet Attached"
.Body = "Please see attached worksheet"
.Attachments.Add FileFullPath
.Display
'.Send You can chose .Send or .Display, as you wish
End With
Kill FileFullPath
'Free the memory
Set OutlookMail = Nothing
Set OutlookApp = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Application.Quit
End Sub
Related
Trying to reference a dynamic range in the body of an email (this will change based on the user's input into the sheet). The email outputs just fine, but there is nothing in the email where "AFund" is supposed to be. Code is below, any help is appreciated!
Dim BlasEmail As Workbook
Dim OutApp As Object
Dim OutMail As Object
Dim FundAdd, FundRem, Broker As Range
Dim AFund As String
Set BlastEmail = ActiveWorkbook
Set Cover = ThisWorkbook.Sheets("Cover")
Set CDEA = ThisWorkbook.Sheets("CDEA")
LastRow = Cells(Rows.Count, 5).End(xlUp).Row
LRow = Cells(Rows.Count, 7).End(xlUp).Row
LasRow = Cells(Rows.Count, 2).End(xlUp).Row
FundAdd = AFund
Set FundAdd = Range("E2:E" & LastRow)
Set FundRem = Range("G2:G" & LRow)
Set Broker = Range("C6:C" & LasRow)
If Range("ISDAMRA") = "ISDA" And Range("G2") = "" Then
Application.ReferenceStyle = xlA1
SigString = Environ("appdata") & _
"\Microsoft\Signatures\My Signature.htm"
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
Set OutApp = CreateObject("Outlook.Application")
Dim EmBody As String
EmBody = "Hello," & "<br><br>" & _
"Body goes here " & "<br>" & "<br>" & AFund
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "myemail"
.CC = ""
.BCC = ""
.Subject = "Here is the subject " & Range("B6") & " "
.HTMLBody = EmBody & Signature
'You can add files like this
'.Attachments.Add ("C:\test.txt")
'.Send
.Display 'This will display the emails for the user to review CXH
End With
On Error GoTo 0
Set OutMail = Nothing
End If
'
End Sub
From:
Sending a range of cells...
2 Methods to Quickly Send Selected Cells in an Excel Worksheet as an Outlook Email
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Sub SendRange()
' https://www.datanumen.com/blogs/2-methods-quickly-send-selected-cells-excel-worksheet-outlook-email/
' https://stackoverflow.com/questions/73136067
Application.Calculation = xlCalculationManual
' Application is Excel. No influence in Outlook.
Application.ScreenUpdating = False
' Reference Microsoft Outlook nn.n Object Library
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Dim olInsp As Outlook.Inspector
' Reference Microsoft Word nn.n Object Library
Dim wdDoc As Word.Document
Dim strGreeting As String
Dim lastRow As Long
lastRow = Cells(Rows.Count, 5).End(xlUp).Row
Debug.Print lastRow
Dim fundAdd As Range
Dim objSelection As Range
Set fundAdd = Range("E2:E" & lastRow)
fundAdd.Select
Set objSelection = Selection
objSelection.Copy
Dim objTempWorkbook As Workbook
Set objTempWorkbook = Workbooks.Add(1)
Dim objTempWorksheet As Worksheet
Set objTempWorksheet = objTempWorkbook.Sheets(1)
Dim strTempHTMLFile As String, Strbody As String
Dim objTempHTMLFile As Object, objTextStream As Object
Dim objFileSystem As Object
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
'Pasting into a Temp Worksheet
With objTempWorksheet.Cells(1)
.PasteSpecial xlPasteColumnWidths
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
'Save the Temp Worksheet as a HTML File
strTempHTMLFile = objFileSystem.GetSpecialFolder(2).Path & _
"\Temp for Excel" & Format(Now, "YYYY-MM-DD hh-mm-ss") & ".htm"
Set objTempHTMLFile = objTempWorkbook.PublishObjects.Add(xlSourceRange, _
strTempHTMLFile, objTempWorksheet.Name, objTempWorksheet.UsedRange.Address)
objTempHTMLFile.Publish (True)
strGreeting = "Hello," & vbNewLine & vbNewLine & _
"Body goes here " & vbNewLine & vbNewLine
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
Set olInsp = .GetInspector ' A side effect is to get the signature
Set wdDoc = olInsp.WordEditor
wdDoc.Range.InsertBefore strGreeting
wdDoc.Paragraphs(5).Range.Paste
'Insert the Temp Worksheet into the Email Body
Dim wb1 As Workbook
Set wb1 = ActiveWorkbook
Dim TempFilePath As String
TempFilePath = Environ$("temp") & "\"
Dim TempFileName As String
TempFileName = "Output Data"
Dim FileExtStr As String
FileExtStr = ".xlsx"
Debug.Print TempFilePath & TempFileName
wb1.SaveAs TempFilePath & TempFileName, FileFormat:=xlOpenXMLWorkbook
.Display
End With
objTempWorkbook.Close (False)
objFileSystem.DeleteFile (strTempHTMLFile)
Kill TempFilePath & TempFileName & FileExtStr 'Delete the temp Excel File
Set olApp = Nothing
Set olEmail = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Hi trying to add a newline between my body content after paste a table and signature,codes are below:
dim FileName As String
Dim filepath As String
Dim rng As Range
Dim OutlookApp As Object
Dim Outlookmail As Object
Dim lastrowo As Integer
Application.ScreenUpdating = False
Set OutlookApp = CreateObject("Outlook.Application")
Set Outlookmail = OutlookApp.CreateItem(0)
lastrowo = Worksheets("Price And Accrued Info").Range("K550").End(xlUp).row
Set rng = Worksheets("Price And Accrued Info").Range("K2:y" & lastrowo)
rng.Copy
Dim vInspector As Object
Set vInspector = Outlookmail.GetInspector
Dim wEditor As Object
Set wEditor = vInspector.WordEditor
With Outlookmail
.To = ""
.cc=""
.Subject = "UNCONFIRMED TRADES AS OF " & Format$(Date, "YYYY.MM.DD")
wEditor.Paragraphs(1).Range.Text = "Hi The following trades are unconfirmed trades."
wEditor.Paragraphs(2).Range.Paste
wEditor.Paragraphs(4).Range.Text = vbNewLine & "<br>"
.display
' .attachments.Add drWorkbook.FullName
' .attachments.Add crWorkbook.FullName
'
End With
Set Outlookmail = Nothing
Set OutlookApp = Nothing
Application.ScreenUpdating = True
Try this:
With Outlookmail
.To = ""
.cc = ""
.Subject = "UNCONFIRMED TRADES AS OF " & Format$(Date, "YYYY.MM.DD")
wEditor.Paragraphs(1).Range.Text = "Hi The following trades are unconfirmed trades." _
& String(5, vbNewLine)
wEditor.Paragraphs(5).Range.Text = "This is is the last line." _
& vbNewLine & vbNewLine
wEditor.Paragraphs(3).Range.Paste
.display
End With
I'm using VBA code from Ron de Bruin that sends every sheet with an email address to the address in a specified cell. It's meant to send the sheet as an attachment.
I want to get data from multiple cells, to put in the body of the email.
I commented out the parts that send the attachment and sent an email that contained data from one cell in the body of the email.
I cannot get data from multiple cells. The email arrives blank.
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("B1").Value Like "?*#?*.?*" Then
sh.Copy
Set wb = ActiveWorkbook
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("B1").Value
.CC = ""
.BCC = ""
.Subject = "Monthly Shirt Sales"
Dim cell As Range
Dim strbody As String
For Each cell In
ThisWorkbook.Sheets("Sheet1").Range("A4:A36")
strbody = strbody & cell.Value & vbNewLine
Next
'.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
It works to send the data from one cell when I replace
Dim cell As Range
Dim strbody As String
For Each cell In ThisWorkbook.Sheets("Sheet1").Range("A4:A36")
strbody = strbody & cell.Value & vbNewLine
Next
with this:
.Body = sh.Range("A4").Value
so I thought that using this would work:
.Body = sh.Range("A4:B36").Value
but it also does not get data and sends a blank email.
How do I get data from multiple cells?
You need to loop through the range and combine the values in the range like in the following example;
Dim strbody As String
For Each cell In sh.Range("A1:B2")
strbody = strbody & cell.Value & vbNewLine
Next cell
Then include the strbody in you outlook with statement
With OutMail
.To = sh.Range("B1").Value
.CC = ""
.BCC = ""
.Subject = "Monthly Shirt Sales"
.Body = strbody
.send 'or use .Display
End With
I have code that splits a workbook based on a condition. I want to email each of those new workbooks to different people.
When I run the macro, it splits the workbook and puts all the worksheets where I want them. When I try to send I only send 1 email.
Sub savesheetsSend()
Dim ws As Worksheet
Dim Filetype As String
Dim Filenum As Long
Dim wb As Workbook
Dim FolderName As String
Dim open_book As Workbook
Set outmail = CreateObject("outlook.application")
Set outmsg = outmail.createitem(0)
Set wb = Application.ThisWorkbook
'create directory to save each sheet in
FolderName = "C:\Users\jpenn\Desktop" & "\" & wb.Name
MkDir FolderName
On Error Resume Next
'save each sheet as workbook in directory
For Each ws In wb.Worksheets
If ws.Range("A1") = 1 Then
Filetype = ".xlsm": Filenum = 52
ws.Copy
xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & Filetype
Application.ActiveWorkbook.SaveAs xFile, FileFormat:=Filenum
End If
Next
'send all new workbooks to email address in CELL("B1")
For Each open_book In Application.Workbooks
If open_book.Name <> ThisWorkbook.Name Then
With outmsg
.Subject = ActiveWorkbook.Name & " payroll data"
.To = ActiveWorkbook.ActiveSheet.Range("b1").Value
.body = "I will get to this later"
.Attachments.Add Application.ActiveWorkbook.FullName
.send
End With
open_book.Close
End If
Next
End Sub
Try it this way... Tested
Option Explicit
Sub savesheetsSend()
Dim Ws As Worksheet
Dim Filetype As String
Dim xFile As String
Dim Filenum As Long
Dim Wb As Workbook
Dim FolderName As String
Dim Open_Book As Workbook
Dim OutMsg As Object
Dim OutMail As Object
Set OutMail = CreateObject("outlook.application")
Set Wb = Application.ThisWorkbook
'create directory to save each sheet in
FolderName = "C:\Users\jpenn\Desktop" & "\" & Wb.Name
MkDir FolderName
'save each sheet as workbook in directory
For Each Ws In Wb.Worksheets
If Ws.Range("A1") = 1 Then
Filetype = ".xlsm": Filenum = 52
Ws.Copy
xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & Filetype
Application.ActiveWorkbook.SaveAs xFile, FileFormat:=Filenum
Set OutMsg = OutMail.createitem(0)
With OutMsg
.Subject = Ws.Name & " payroll data"
.To = ActiveSheet.Range("b1").Value
.Body = "I will get to this later"
.Attachments.Add (xFile)
.Display
End With
ActiveWorkbook.Close
End If
Next
End Sub
I have a vba code which works fine, but I want to create the same code as batch file which can do the same thing the vba code is doing.
I have created the code which sends all files in a folder to a specified email address and after sending delete the file.
Can anyone help me in creating the same thing with a batch file which can do the same thing.
Below is the VBA code:
Private Sub Click()
Dim mess_body As String, StrFile As String, StrPath As String
Dim appOutLook As Outlook.Application
Dim MailOutLook As Outlook.MailItem
Set appOutLook = CreateObject("Outlook.Application")
Set MailOutLook = appOutLook.CreateItem(olMailItem)
'~~> Change path here
StrPath = "\Project\New folder\New folder\"
With MailOutLook
.BodyFormat = olFormatRichText
.To = "test#sdm.com"
.Subject = "test"
.HTMLBody = "test"
'~~> *.* for all files
StrFile = Dir(StrPath & "*.*")
Do While Len(StrFile) > 0
.Attachments.Add StrPath & StrFile
StrFile = Dir
Loop
'.DeleteAfterSubmit = True
.Send
End With
Kill "\Project\New folder\New folder\*.*"
MsgBox "Reports have been sent", vbOKOnly
End Sub
U can use cell ("A1") value as folder reference.
Dim objFolder As Object
Set appOutLook = CreateObject("Outlook.Application")
Set MailOutLook = appOutLook.CreateItem(olMailItem)
'~~> Change path here
VAR1 = Range("A1").Value
If VAR1 = False Then MsgBox "Cell is empty"
If VAR1 = False Then Exit Sub
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(VAR1)
With MailOutLook
.BodyFormat = olFormatRichText
.To = "test#test.com"
.Subject = "test"
.HTMLBody = "test"
'~~> *.* for all files
StrFile = Dir(objFolder & "*.*")
...
'.DeleteAfterSubmit = True
.Send
End With
'delete files
Kill objFolder & "\*.*"