Worksheet_Calculate repeats until I force quit Excel - excel

I have a working VBA script that generates an Outlook email when cell value = 1. This runs on a hidden worksheet (cell is changed to 1 when criteria is met on visible summary worksheet).
Dim xRg As Range
'Update by Extendoffice 2019/8/2
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Cells.Count > 1 Then Exit Sub
Set xRg = Intersect(Range("AA1"), Target)
If xRg Is Nothing Then Exit Sub
If IsNumeric(Target.Value) And Target.Value = 1 Then
Call Mail_small_Text_Outlook
End If
End Sub
Sub Mail_small_Text_Outlook()
Dim xOutApp As Object
Dim xOutMail As Object
Dim xMailBody As String
Set xOutApp = CreateObject("Outlook.Application")
Set xOutMail = xOutApp.CreateItem(0)
xMailBody = "Hello " & Range("G2") & "," & vbNewLine & vbNewLine & _
"Please review the following list of loan documents that were produced through our online system from " & Range("A2") & ". Your total bill for this month's documents is " & FormatCurrency(Range("E2")) & " (" & Range("C2") & " x " & Range("D2") & "):" & vbNewLine & vbNewLine & _
Range("F2") & vbNewLine & _
Range("F3") & vbNewLine & _
Range("F4") & vbNewLine & _
Range("F5") & vbNewLine & _
Range("F6") & vbNewLine & _
Range("F7") & vbNewLine & _
Range("F8") & vbNewLine & _
Range("F9") & vbNewLine & _
Range("F10") & vbNewLine & _
Range("F11") & vbNewLine & _
Range("F12") & vbNewLine & _
Range("F13") & vbNewLine & _
Range("F14") & vbNewLine & _
Range("F15") & vbNewLine & _
Range("F16") & vbNewLine & _
Range("F17") & vbNewLine & _
Range("F18") & vbNewLine & _
Range("F19") & vbNewLine & _
Range("F19") & vbNewLine & _
Range("F20") & " " & Range("F21") & " " & Range("F22") & " " & Range("F23") & " " & Range("F24") & " " & Range("F25") & " " & Range("F26") & " " & Range("F27") & " " & Range("F28") & " " & Range("F29") & " " & Range("F30") & " " & Range("F31") & " " & Range("F32") & " " & Range("F33") & " " & Range("F34") & " " & Range("F35") & " " & Range("F36") & " " & Range("F37") & " " & Range("F38") & " " & Range("F39") & " " & Range("F40") & " " & Range("F41") & " " & Range("F42") & " " & Range("F43") & " " & Range("F44") & " " & Range("F45") & " " & Range("F46") & " " & Range("F47") & " " & Range("F48") & " " & Range("F49") & " " & Range("F50") & " " & Range("F51") & " " & Range("F52") & " " & Range("F53") & " " & Range("F54") & " " & vbNewLine & _
Range("F55") & " " & Range("F56") & " " & Range("F57") & " " & Range("F58") & " " & Range("F59") & " " & Range("F60") & " " & Range("F61") & " " & Range("F62") & " " & Range("F63") & " " & Range("F64") & " " & Range("F65") & " " & Range("F66") & " " & Range("F67") & " " & Range("F68") & " " & Range("F69") & " " & Range("F70") & " " & Range("F71") & " " & Range("F72") & " " & Range("F73") & " " & Range("F74") & " " & Range("F75") & " " & Range("F76") & " " & Range("F77") & " " & Range("F78") & " " & Range("F79") & " " & Range("F80") & " " & Range("F81") & " " & Range("F82") & " " & Range("F83") & " " & Range("F84") & " " & Range("F85") & " " & Range("F86") & " " & Range("F87") & " " & Range("F88") & " " & Range("F89") & " " & vbNewLine & vbNewLine & _
"Please let us know within two business days whether your records match ours. If we do not get a response within this time frame, we will invoice you shortly thereafter. If your credit card is on file and we have a pre-existing authorization, we will charge your card on file and provide you with a copy of your paid invoice." & vbNewLine & vbNewLine & _
"Thank you!" & vbNewLine
On Error Resume Next
With xOutMail
.To = Range("H2")
.CC = "billing#example.com"
.BCC = ""
.Subject = Range("B2") & " - (ID: " & Range("I2") & ") - " & Range("A2") & " Lightning Docs Usage & Billing"
.Body = xMailBody
.Display 'or use .Send
End With
On Error GoTo 0
Set xOutMail = Nothing
Set xOutApp = Nothing
End Sub
Private Sub Worksheet_Calculate()
Dim xI As Integer
Dim xRg As Range
Set xRg = Range("AA1")
On Error GoTo Err01
xI = Int(xRg.Value)
If xI = 1 Then
Call Mail_small_Text_Outlook
End If
Err01:
End Sub
This is a bodge way of adding what should be a table into the email body.
I recently discovered Ron de Bruin's script for converting a table to HTML and adding it to an email body that way. I got the script running, but my problem comes when trying to trigger the macro from another worksheet. The user will be on the summary worksheet and make a change to cause cell AA1 on the VBA script worksheet to change to 1.
Without Private Sub Worksheet_Calculate(), it works when I am on the worksheet with the script.
When I add Private Sub Worksheet_Calculate(), it can be triggered from a different worksheet, but it gets stuck at the point where a temporary worksheet is created, and keeps creating temporary worksheets until I force quit Excel.
Dim xRg As Range
'Update by Extendoffice 2018/3/7
Public Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Cells.Count > 1 Then Exit Sub
Set xRg = Intersect(Range("AA1"), Target)
If xRg Is Nothing Then Exit Sub
If IsNumeric(Target.Value) And Target.Value > 0 Then
Call Mail_small_Text_Outlook
End If
End Sub
Sub Mail_small_Text_Outlook()
Dim xOutApp As Object
Dim xOutMail As Object
Dim xMailBody As String
Set xOutApp = CreateObject("Outlook.Application")
Set xOutMail = xOutApp.CreateItem(0)
On Error Resume Next
With xOutMail
.To = Range("H2")
.CC = "billing#example.com"
.BCC = ""
.Subject = Range("C2") & " - (ID: " & Range("I2") & ") - " & Range("B2") & " Lightning Docs Usage & Billing"
.HTMLBody = "<font size=-0> Hello " & Range("G2") & ",<br/><br/>" &
"Please review the following list of loan documents that were produced through our online system from " & Range("B2") & ". <br/>Your total bill for this month's documents is " & FormatCurrency(Range("F2")) & " (" & Range("E2") & " x " & FormatCurrency(Range("D2")) & "):</font>" &
RangetoHTML(Range("Table3_2[Titles]")) &
"<br/><font size=-0>Please let us know within two business days whether your records match ours. If we do not get a response within this time frame, we will invoice you shortly thereafter. If your credit card is on file and we have a pre-existing authorization, we will charge your card on file and provide you with a copy of your paid invoice." &
"<br/><br/>Thank you!</font><br/>"
.Display 'or use .Send
End With
On Error GoTo 0
Set xOutMail = Nothing
Set xOutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Private Sub Worksheet_Calculate()
Dim xI As Integer
Dim xRg As Range
Set xRg = Range("AA1")
On Error GoTo Err01
xI = Int(xRg.Value)
If xI = 1 Then
Call Mail_small_Text_Outlook
End If
Err01:
End Sub

Related

Bypass code to insert cell values where cell is empty

I have the following listed in my Sheet 1 code, moving cell values to the body of an Outlook email.
I'm trying to STOP inserting text for the given line if the cell in Column A is empty.
Private Sub CommandButton1_Click()
'Create email with attachment, subject, and list of email addresses
ThisWorkbook.Save
Dim outlookApp As Object
Dim myMail As Object
Dim Source_File, to_emails, cc_emails As String
Dim file_to_send As String
Dim body_code As String
Dim i As Integer
Set outlookApp = CreateObject("Outlook.Application")
Set myMail = outlookApp.CreateItem(olMailItem)
For i = 2 To 22
to_emails = to_emails & Cells(i, 13) & ";"
'for CC: change the 13 to whatever column count from the left where your CC list is
'cc_emails = cc_emails & Cells(i, 13) & ";"
Next i
Source_File = ThisWorkbook.FullName
myMail.Attachments.Add Source_File
'myMail.CC = cc_emails
myMail.To = to_emails
myMail.Subject = Range("Q2").Value & " 10-8 Form " & Format(Date, "mm/dd/yy")
myMail.Body = Range("B2") & " Shift" & " - " & Format(Date, "mmmm dd, yyyy") _
& vbNewLine & vbNewLine & "Sergeant: " & Range("A6") & ", " & Range("B6") & vbNewLine & " Status: " & Range("C6") _
& vbNewLine & vbNewLine & "Corporal: " & Range("A8") & ", " & Range("B8") & vbNewLine & " Status: " & Range("C8") _
& vbNewLine & vbNewLine & "Assigned Deputies" & vbNewLine & vbNewLine & _
Range("A10") & ", " & Range("B10") & vbNewLine & " Assignment/Zone: " & Range("C10") & vbNewLine & _
Range("A11") & ", " & Range("B11") & vbNewLine & " Assignment/Zone: " & Range("C11") & vbNewLine & _
Range("A12") & ", " & Range("B12") & vbNewLine & " Assignment/Zone: " & Range("C12") & vbNewLine & _
Range("A13") & ", " & Range("B13") & vbNewLine & " Assignment/Zone: " & Range("C13") & vbNewLine & _
Range("A14") & ", " & Range("B14") & vbNewLine & " Assignment/Zone: " & Range("C14") & vbNewLine & _
Range("A15") & ", " & Range("B15") & vbNewLine & " Assignment/Zone: " & Range("C15") & vbNewLine & _
Range("A16") & ", " & Range("B16") & vbNewLine & " Assignment/Zone: " & Range("C16") & vbNewLine & _
Range("A17") & ", " & Range("B17") & vbNewLine & " Assignment/Zone: " & Range("C17") & vbNewLine & _
Range("A18") & ", " & Range("B18") & vbNewLine & " Assignment/Zone: " & Range("C18")
myMail.Display
ThisWorkbook.Save
End Sub
I would definitely break up that huge wall of text you have. This can be done with a loop.
Let's use a For loop here.
Dim concatString as String
For i = 10 To 18
If Not Cells(i, "A").Text = vbNullString Then
'Add to growing string
concatString = concatString + Cells(i, "A").Text & ", " & Cells(i, "B").Text & vbCr
concatString = concatString + "Assignment/Zone: " & Cells(i, "C").Text & vbCr
End If
Next i
If column A contains an empty string, we skip over it and move to the next row.
I posted this before you added more code, but I think you get the idea. Break up the huge chunk of code, and put only one cycle through columns A, B, and C in the loop. Adjust your loop constraints as necessary.
Here's what it would look like in your code:
'...
'your code here
'...
Dim concatString as String
For i = 10 To 18
If Not Cells(i, "A").Text = vbNullString Then
'Add to growing string
concatString = concatString + Cells(i, "A").Text & ", " & Cells(i, "B").Text & vbCr
concatString = concatString + "Assignment/Zone: " & Cells(i, "C").Text & vbCr
End If
Next i
myMail.Body = Range("B2") & " Shift" & " - " & Format(Date, "mmmm dd, yyyy") _
& vbNewLine & vbNewLine & "Sergeant: " & Range("A6") & ", " & Range("B6") & vbNewLine & " Status: " & Range("C6") _
& vbNewLine & vbNewLine & "Corporal: " & Range("A8") & ", " & Range("B8") & vbNewLine & " Status: " & Range("C8") _
& vbNewLine & vbNewLine & "Assigned Deputies" & vbNewLine & vbNewLine & concatString
I removed all those extra spaces, not sure if you actually need them in there or if it's a vestige of copying/pasting from VBE.
Here is the final code, the one that finally did it. Thank you to jclasley
`Private Sub CommandButton1_Click()
'Create email with attachment, subject, and list of email addresses
ThisWorkbook.Save
Dim outlookApp As Object
Dim myMail As Object
Dim Source_File, to_emails, cc_emails As String
Dim file_to_send As String
Dim i As Integer
Dim concatString As String
Set outlookApp = CreateObject("Outlook.Application")
Set myMail = outlookApp.CreateItem(olMailItem)
For i = 2 To 22
to_emails = to_emails & Cells(i, "M") & ";"
'for CC: change the 13 to whatever column count from the left where your CC list is
'cc_emails = cc_emails & Cells(i, 13) & ";"
Next i
Source_File = ThisWorkbook.FullName
myMail.Attachments.Add Source_File
'myMail.CC = cc_emails
myMail.To = to_emails
myMail.Subject = Range("Q2").Value & " 10-8 Form " & Format(Date, "mm/dd/yy")
For i = 10 To 18
If Not Cells(i, "A").Text = vbNullString Then
'Add to growing string
concatString = concatString + Cells(i, "A").Text & ", " & Cells(i, "B").Text & vbCr
concatString = concatString + "Assignment/Zone: " & Cells(i, "C").Text & vbNewLine & vbCr
End If
Next i
myMail.Body = Range("B2") & " Shift" & " - " & Format(Date, "mmmm dd, yyyy") _
& vbNewLine & vbNewLine & "Sergeant: " & Range("A6") & ", " & Range("B6") & vbNewLine & " Status: " & Range("C6") _
& vbNewLine & vbNewLine & "Corporal: " & Range("A8") & ", " & Range("B8") & vbNewLine & " Status: " & Range("C8") _
& vbNewLine & vbNewLine & "Assigned Deputies" & vbNewLine & vbNewLine & concatString
myMail.Display
ThisWorkbook.Save
End Sub
enter code here

Change the format in text pasted to Outlook

I am trying to change the text so certain values from cells are either bold, underlined, red, or otherwise stand out from the surrounding text in the body of the email.
How can I do that?
For i = 10 To 18
If Not Cells(i, "A").Text = vbNullString Then
'Add to growing string
concatString = concatString + Cells(i, "A").Text & ", " & _
Cells(i, "B").Text & vbCr
concatString = concatString + "Assignment/Zone: " & _
Cells(i, "C").Text & vbNewLine & vbCr
End If
Next i
myMail.Body = Range("B2") & " Shift" & " - " & Format(Date, "mmmm dd, yyyy") _
& vbNewLine & vbNewLine & "Sergeant: " & Range("A6") & ", " & Range("B6") & _
vbNewLine & " Status: " & Range("C6") _
& vbNewLine & vbNewLine & "Corporal: " & Range("A8") & ", " & Range("B8") & _
vbNewLine & " Status: " & Range("C8") _
& vbNewLine & vbNewLine & "Assigned Deputies" & vbNewLine & vbNewLine & concatString
You need to look into using HTML-formatted content to apply the colors etc you want:
Dim oApp As Object, oMail As Object
Set oApp = CreateObject("outlook.application")
Set oMail = oApp.createitem(0)
oMail.Display
oMail.htmlBody = "<h1>This is a heading</h1>" & _
"<p style='color:#F00'>Some red text</p>" & _
"<p><u>Underlined</u></p>" & _
"<p><b>Bold</b></p>" & _
"<p><i>Italic</i></p>"
I needed to use <br> to put the resultant answer in the email body. <p> creates a new PARAGRAPH, while <br> just puts it on the next line.
& "<br><b><u>Status:</u></b>"
gives:
& "Status:" &
Instead of:
& "<p><b><u>Status:</u></b>"
Which gives:
& "Status:"
Thank you for your help!

Excel VBA to loop data into email body

I am trying to create a loop within VBA to have multiple selections from userform1's listbox2 when I hit the command button to draft an email with each selection in the following format. However, I can't figure out how to get more than just one selection into the body of the email. I tried to separate it into a "midbody" and add the code again, but it just adds the same entry twice. How can I make this loop work?
Private Sub CommandButton3_Click()
Dim objOutlook As Object
Dim objMail As Object
Dim midBody As String
Dim wksheet As String
Dim i As Integer
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
For i = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(i) = True Then
wksheet = ListBox2.List(i)
Sheets(wksheet).Activate
End If
If wksheet = "" Then
MsgBox "Nothing is Selected"
objMail.To = "myemail#me.com"
'objMail.CC =
objMail.Subject = ""
Else
midBody = activesheet.Range("C" & Rows.Count).End(xlUp).Value & vbNewLine & _
activesheet.Range("D" & Rows.Count).End(xlUp).Value & " through " & activesheet.Range("E" & Rows.Count).End(xlUp).Value & " phase" & vbNewLine & _
"Phase ECD: " & activesheet.Range("F" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Baseline Finish: " & activesheet.Range("G" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Previous Finish: " & activesheet.Range("H" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Current Finish: " & activesheet.Range("I" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Weekly Schedule Variance: " & activesheet.Range("J" & Rows.Count).End(xlUp).Value & vbNewLine & _
"CUM VAR to Baseline: " & activesheet.Range("K" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Slip Reason: " & vbNewLine & _
"Critical Path: " & vbNewLine & vbNewLine
objMail.body = midBody & Sheets.Range("C" & Rows.Count).End(xlUp).Value & vbNewLine & _
Sheets.Range("D" & Rows.Count).End(xlUp).Value & " through " & Sheets.Range("E" & Rows.Count).End(xlUp).Value & " phase" & vbNewLine & _
"Phase ECD: " & Sheets.Range("F" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Baseline Finish: " & Sheets.Range("G" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Previous Finish: " & Sheets.Range("H" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Current Finish: " & Sheets.Range("I" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Weekly Schedule Variance: " & Sheets.Range("J" & Rows.Count).End(xlUp).Value & vbNewLine & _
"CUM VAR to Baseline: " & Sheets.Range("K" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Slip Reason: " & vbNewLine & _
"Critical Path: " & vbNewLine & vbNewLine
End If
i = i + 1
Next i
objMail.Save
'Close the object
Set objMail = Nothing
MsgBox "Done", vbInformation
End Sub
I have made some changes in your code .Shifted Next of For towards later part of the code to include processing of loop. Removed redundant midBody.
Try This:
Private Sub CommandButton3_Click()
Dim ws As Worksheet
Dim i As Integer
Dim Agent As String
Dim EmailID As String
Dim wksheet As String
Dim objOutlook As Object
Dim objMail As Object
With Me.ListBox2
For i = 0 To .ListCount - 1
If .Selected(i) Then
wksheet = .List(i)
Exit For
End If
End With
If wksheet = "" Then
MsgBox "Nothing is Selected", vbExclamation
Exit Sub
End If
'r = Application.Match(wksheet, mySheet.Columns(1), 0)'choose one as per your data structure
r = Application.Match(Agent, mySheet.Columns(1), 0) 'choose one as per your data structure
Set ws = ThisWorkbook.ActiveSheet
'EmailID = mySheet.Range("D" & r).Value 'Uncomment it if this is required
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With objMail
.To = "myemail#me.com" ' Or EmailID
' .CC =
.subject = ""
.Body = ActiveSheet.Range("C" & Rows.Count).End(xlUp).Value & vbNewLine & _
ActiveSheet.Range("D" & Rows.Count).End(xlUp).Value & " through " & ActiveSheet.Range("E" & Rows.Count).End(xlUp).Value & " phase" & vbNewLine & _
"Phase ECD: " & ActiveSheet.Range("F" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Baseline Finish: " & ActiveSheet.Range("G" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Previous Finish: " & ActiveSheet.Range("H" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Current Finish: " & ActiveSheet.Range("I" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Weekly Schedule Variance: " & ActiveSheet.Range("J" & Rows.Count).End(xlUp).Value & vbNewLine & _
"CUM VAR to Baseline: " & ActiveSheet.Range("K" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Slip Reason: " & vbNewLine & _
"Critical Path: " & vbNewLine & vbNewLine
'.Display
'.Send
.Save
End With
Next i
Set objMail = Nothing
Set objOutlook = Nothing
MsgBox "Done", vbInformation
End Sub
EDIT: Another version of code which works at my end. I have not created a listbox but simulated its working. This program loops correctly and send emails multiple times. Please remove k variable as per your listbox code . It is only for checking correct looping of the ptogram. Earlier version of program can be adjusted to your requirements if you provide sample data as what is the structure of listbox, from where it is picking emailid of the recipient, sample data of your worksheet etc.
Private Sub Command3_Click()
Dim subject As String, Body As String
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Dim ws As Worksheet
Dim k As Integer
On Error Resume Next
Set ws = ThisWorkbook.ActiveSheet
Set OutApp = GetObject(, "Outlook.Application")
If OutApp Is Nothing Then
Set OutApp = CreateObject("Outlook.Application")
End If
On Error GoTo 0
k = 4 ' remove it only for checking correct loop
For intCurrentRow = 0 To k - 1 'List2.ListCount change k to List2.ListCount
Set OutMail = OutApp.CreateItem(olMailItem)
With OutMail
' List2.Selected(intCurrentRow) = True ' This is to be commented out after trials for looping
.To = "abc#gmail.com"
.subject = "Test 2nd time Email"
.Body = ActiveSheet.Range("C" & Rows.Count).End(xlUp).Value & vbNewLine & _
ActiveSheet.Range("D" & Rows.Count).End(xlUp).Value & " through " & ActiveSheet.Range("E" & Rows.Count).End(xlUp).Value & " phase" & vbNewLine & _
"Phase ECD: " & ActiveSheet.Range("F" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Baseline Finish: " & ActiveSheet.Range("G" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Previous Finish: " & ActiveSheet.Range("H" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Current Finish: " & ActiveSheet.Range("I" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Weekly Schedule Variance: " & ActiveSheet.Range("J" & Rows.Count).End(xlUp).Value & vbNewLine & _
"CUM VAR to Baseline: " & ActiveSheet.Range("K" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Slip Reason: " & vbNewLine & _
"Critical Path: " & vbNewLine & vbNewLine
.Send
End With
Next intCurrentRow
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Outlook snapshot shows it is looping properly which was your main problem.
EDIT2: Earlier version of program simulated at my end on sample basis is running correctly and sending multiple mails. I do not have idea of your data setup so simulated for looping which was your main problem. Please try the program as it is , retain a copy and then make suitable adjustments for your data specific situation.
Private Sub CommandButton3_Click()
Dim ws As Worksheet
Dim i As Integer
Dim Agent As String
Dim EmailID As String
Dim wksheet As String
Dim objOutlook As Object
Dim objMail As Object
' With Me.ListBox2
For i = 1 To 3
'For i = 0 To .ListCount - 1
' If .Selected(i) Then
' wksheet = .List(i)
' Exit For
' End If
'End With
If wksheet = "hello" Then
MsgBox "Nothing is Selected", vbExclamation
Exit Sub
End If
'r = Application.Match(wksheet, mySheet.Columns(1), 0)'choose one as per your data structure
' r = Application.Match(Agent, mySheet.Columns(1), 0) 'choose one as per your data structure
Set ws = ThisWorkbook.ActiveSheet
'EmailID = mySheet.Range("D" & r).Value 'Uncomment it if this is required
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With objMail
.To = "abc#gmail.com" ' Or EmailID
' .CC =
.subject = "original test"
.Body = ActiveSheet.Range("C" & Rows.Count).End(xlUp).Value & vbNewLine & _
ActiveSheet.Range("D" & Rows.Count).End(xlUp).Value & " through " & ActiveSheet.Range("E" & Rows.Count).End(xlUp).Value & " phase" & vbNewLine & _
"Phase ECD: " & ActiveSheet.Range("F" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Baseline Finish: " & ActiveSheet.Range("G" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Previous Finish: " & ActiveSheet.Range("H" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Current Finish: " & ActiveSheet.Range("I" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Weekly Schedule Variance: " & ActiveSheet.Range("J" & Rows.Count).End(xlUp).Value & vbNewLine & _
"CUM VAR to Baseline: " & ActiveSheet.Range("K" & Rows.Count).End(xlUp).Value & vbNewLine & _
"Slip Reason: " & vbNewLine & _
"Critical Path: " & vbNewLine & vbNewLine
'.Display
.Send
'.Save
End With
Next i
Set objMail = Nothing
Set objOutlook = Nothing
MsgBox "Done", vbInformation
End Sub

need help fixing my code for sending automatic emails through vba

I have recently written a code that allows me to send an email to a specific person in a range when clicking the command button. My code originally was working fine, however, I wanted to reference my range of these peoples emails on another sheet named "Parameter" instead of the active sheet.
When I changed my code it worked but instead of sending one email it sent three. I need help ending my code so that it will only send one email.
Private Sub JLechner_Click()
Dim sh As Worksheet
Dim sh2 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") & "\"
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")
Set sh2 = ThisWorkbook.Sheets("Parameter")
For Each sh In ThisWorkbook.Worksheets
If sh2.Range("K8").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
strbody = "(See below for english version)" & vbNewLine & vbNewLine & _
"Hallo," & vbNewLine & vbNewLine & _
"Maß " & sh.Range("E4").Value & " muss geprüft werden." & vbNewLine & _
"Bitte im Sharepoint die prüfung durchführen." & vbNewLine & vbNewLine & _
"Die Maßnahmenblätter finden Sie unter folgendem Link:" & vbNewLine & vbNewLine & _
"Wenn die Prüfung abgeschlossen ist, bitte die Taste auf der rechten Seite der tabelle drücken, um die Maßnahme zum folgendem Bearbeiter weiterzuleiten." & vbNewLine & _
"Wenn Sie Unterstützung brauchen, bitte kontaktieren Sie Bob and Ryan." & vbNewLine & vbNewLine & _
"Vielen Dank." & vbNewLine & _
"Mit freundlichen Grüßen" & vbNewLine & _
"Team" & vbNewLine & vbNewLine & vbNewLine & _
"----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" & vbNewLine & vbNewLine & vbNewLine & _
"Hello," & vbNewLine & vbNewLine & _
"Measure " & sh.Range("E4").Value & " must be checked." & vbNewLine & _
"Please access the Sharepoint and proceed with your corresponding check." & vbNewLine & vbNewLine & _
"Measures can be found using the following link:" & vbNewLine & vbNewLine & _
"When finished, please forward the measure to the next responsible person using the buttons on the right side of the table." & vbNewLine & _
"If you require support, contact any MTM responsible persons." & vbNewLine & vbNewLine & _
"Thank you," & vbNewLine & _
"Best regards," & vbNewLine & _
"Team"
On Error Resume Next
With OutMail
.To = sh2.Range("K8").Value
.CC = ""
.BCC = ""
.Subject = "Bitte Maßnahmenblatt bearbeiten: " & sh.Range("E4").Value
.Body = strbody
.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
Please let me know if anyone can help me with this.
I think you need to just change this
For Each sh In ThisWorkbook.Worksheets
If sh2.Range("K8").Value Like "?*#?*.?*" Then
to this
For Each sh In ThisWorkbook.Worksheets
If sh.Range("K8").Value Like "?*#?*.?*" Then
Because you are looping over every sheet but checking condition for sheet Parameter everytime which results TRUE for every worksheet.

print variable to output text file in excel 2010 vba

The below excel 2010 vba runs perfectly except I can not seem to get the variable process (time elapsed) to print from the Call Perl section to the analysis.txt, which captures some information regarding the analysis. Thank you :).
Private Sub CommandButton3_Click()
Dim MyBarCode As String ' Enter Barcode
Dim MyScan As String ' Enter ScanDate
Dim MyDirectory As String
'GET USER INPUT '
Line1:
MyBarCode = Application.InputBox("Please enter the last 5 digits of the barcode", "Bar Code", Type:=2)
If MyBarCode = "False" Then Exit Sub 'user canceled
Do
MyScan = Application.InputBox("Please enter scan date", "Scan Date", Date - 1, Type:=2)
If MyScan = "False" Then Exit Sub 'user canceled
If IsDate(MyScan) Then Exit Do
MsgBox "Please enter a valid date format. ", vbExclamation, "Invalid Date Entry"
Loop
'CREATE NEXUS DIRECTORY AND VERIFY FOLDER '
MyDirectory = "N:\1_DATA\MicroArray\NexusData\" & "2571683" & MyBarCode & "_" & Format(CDate(MyScan), "m-d-yyyy") & "\"
If Dir(MyDirectory, vbDirectory) = "" Then
MkDir MyDirectory
Else
MsgBox ("Already exsists! Please enter again")
GoTo Line1
End If
'Write to text file
Open MyDirectory & "sample_descriptor.txt" For Output As #1
Print #1, "Experiment Sample" & vbTab & "Control Sample" & vbTab & "Display Name" & vbTab & "Gender" & vbTab & "Control Gender" & vbTab & "Spikein" & vbTab & "Location" & vbTab & "Barcode" & vbTab & "Medical Record" & vbTab & "Date of Birth" & vbTab & "Order Date"
Print #1, "2571683" & MyBarCode & "_532Block1.txt" & vbTab & "2571683" & MyBarCode & "_635Block1.txt" & vbTab & ActiveSheet.Range("B8").Value & " " & ActiveSheet.Range("B9").Value & vbTab & ActiveSheet.Range("B10").Value & vbTab & ActiveSheet.Range("B5").Value & vbTab & ActiveSheet.Range("B11").Value & vbTab & ActiveSheet.Range("B12").Value & vbTab & "2571683" & MyBarCode & vbTab & ActiveSheet.Range("C201").Value & vbTab & ActiveSheet.Range("D201").Value & vbTab & ActiveSheet.Range("E201").Value
Print #1, "2571683" & MyBarCode & "_532Block2.txt" & vbTab & "2571683" & MyBarCode & "_635Block2.txt" & vbTab & ActiveSheet.Range("C8").Value & " " & ActiveSheet.Range("C9").Value & vbTab & ActiveSheet.Range("C10").Value & vbTab & ActiveSheet.Range("C5").Value & vbTab & ActiveSheet.Range("C11").Value & vbTab & ActiveSheet.Range("C12").Value & vbTab & "2571683" & MyBarCode & vbTab & ActiveSheet.Range("C202").Value & vbTab & ActiveSheet.Range("D202").Value & vbTab & ActiveSheet.Range("E202").Value
Print #1, "2571683" & MyBarCode & "_532Block3.txt" & vbTab & "2571683" & MyBarCode & "_635Block3.txt" & vbTab & ActiveSheet.Range("D8").Value & " " & ActiveSheet.Range("D9").Value & vbTab & ActiveSheet.Range("D10").Value & vbTab & ActiveSheet.Range("D5").Value & vbTab & ActiveSheet.Range("D11").Value & vbTab & ActiveSheet.Range("D12").Value & vbTab & "2571683" & MyBarCode & vbTab & ActiveSheet.Range("C203").Value & vbTab & ActiveSheet.Range("D203").Value & vbTab & ActiveSheet.Range("E203").Value
Print #1, "2571683" & MyBarCode & "_532Block4.txt" & vbTab & "2571683" & MyBarCode & "_635Block4.txt" & vbTab & ActiveSheet.Range("E8").Value & " " & ActiveSheet.Range("E9").Value & vbTab & ActiveSheet.Range("E10").Value & vbTab & ActiveSheet.Range("E5").Value & vbTab & ActiveSheet.Range("E11").Value & vbTab & ActiveSheet.Range("E12").Value & vbTab & "2571683" & MyBarCode & vbTab & ActiveSheet.Range("C201").Value & vbTab & ActiveSheet.Range("D204").Value & vbTab & ActiveSheet.Range("E204").Value
Close #1
'CREATE ANALYSIS LOG '
Dim Process As String
Open MyDirectory & "analysis.txt" For Output As #2
Print #2, "Analysis done by" & " " & Environ("UserName") & " " & "on" & " " & Date & " " & "at" & " " & Time & " " & "and took" & Process & "to complete"
Close #2
'CONFIRM ENTRIES '
Dim Patient As String
Dim Barcode As String
Dim Directory As String
Dim MyFile As Variant
Dim MyFolder As String
Dim i As Long
Directory = "N:\1_DATA\MicroArray\NexusData\" & "2571683" & MyBarCode & "_" & Format(CDate(MyScan), "m-d-yyyy")
Patient = ActiveSheet.Range("B9").Value & " " & ActiveSheet.Range("C9").Value & " " & ActiveSheet.Range("D9").Value & " " & ActiveSheet.Range("E9").Value
Barcode = "2571683" & MyBarCode
MsgBox "The patients that will be analyzed are:" + Patient & "The barcode is:" + Barcode
iYesNo = MsgBox("Do the patients and barcode match the setup sheet?", vbYesNoCancel)
Select Case iYesNo
Case vbYes
GoTo Line2
Case vbNo
MsgBox ("Doesn't match! Please enter again")
Call DeleteFolder(Directory)
GoTo Line1
End Select
'ADD VBA REFERENCE: MICROSOFT XML, v3.0 or v6.0 '
Line2:
Dim oXMLFile As New MSXML2.DOMDocument
Dim imgNode As MSXML2.IXMLDOMNodeList, destNode As MSXML2.IXMLDOMNodeList
Dim XML­File­Name As String
XML­File­Name = "C:\Users\cmccabe\Desktop\EmArray\Design\imagene.bch"
oXMLFile.Load (XML­File­Name)
'EXTRACT NODES INTO LIST AND REWRITE NODES '
Set imgNode = oXMLFile.DocumentElement.SelectNodes("/Batch/Entry/Image")
imgNode(0).Text = "I:\" & "2571683" & MyBarCode & "_532.tif"
imgNode(1).Text = "I:\" & "2571683" & MyBarCode & "_635.tif"
Set destNode = oXMLFile.DocumentElement.SelectNodes("/Batch/Entry/Destination")
destNode(0).Text = MyDirectory
destNode(1).Text = MyDirectory
'SAVE UPDATED XML '
oXMLFile.Save XML­File­Name
'UNINTIALIZE OBJECTS '
Set imgNode = Nothing
Set destNode = Nothing
Set oXMLFile = Nothing
'CALCULATE TIME FOR PROCESS '
Dim StartTime As Double
Dim MinutesElapsed As String
StartTime = Timer ' define start time
'CALL JAVA PROGRAM USING SHELL AND COMPLETE PROCESS '
Dim wshell As Object
Set wshell = CreateObject("wscript.shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wshell.Run Chr(34) & "C:\Users\cmccabe\Desktop\EmArray\Design\java.bat", windowsStyle, waitOnReturn
'UPDATE PERL VARIABLES USING SHELL '
Dim PerlCommand As String, PerlParameters As String, VarDirectory As String
Dim var As String, var1 As String, var2 As String, var3 As String
MsgBox ("Verifying spike-ins, please wait")
VarDirectory = "N:\1_DATA\MicroArray\NexusData\" & "2571683" & MyBarCode & "_" & Format(CDate(MyScan), "m-d-yyyy")
var = VarDirectory
var1 = "sample_descriptor.txt"
var2 = "C:\cygwin\home\cmccabe\test_probes8.txt"
var3 = var & "\" & "output.txt"
'CALL PERL '
PerlCommand = """C:\Users\cmccabe\Desktop\EmArray\Design\perl.bat"""
PerlParameters = """" & var & """" & " " & _
"""" & var1 & """" & " " & _
"""" & var2 & """" & " " & _
"""" & var3 & """"
CreateObject("wscript.shell").Run PerlCommand & " " & PerlParameters, windowsStyle, waitOnReturn
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss") 'elapsed seconds
Process = MinutesElapsed & " minutes"
iYesNo = MsgBox("ImaGene and spike-in anlysis complete, do you want to run NxClinical?", vbYesNoCancel)
Select Case iYesNo
Case vbYes
'CALL AND EXECUTE NXCLINICAL '
Dim x As Variant
Dim Path As String
'SET INSTALLATION PATH '
Path = "C:\Program Files\BioDiscovery\NxClinical Client\NxClinical.exe"
x = Shell(Path, vbNormalFocus)
Case vbNo
'CLOSE AND EXIT '
Application.DisplayAlerts = False
Application.Quit
End Select
End Sub

Resources