Excel VBA Add Spaces to Cells - vba

I have 10 columns of data with a varying number of rows which is emailed as an unformatted range. I want to be able to right pad the cells in each column with spaces so the unformatted range copies over as evenly spaced. The reason the range is unformatted is I am using LotusNotes and I don't have the integration options like I have with Outlook. Is there anyway without adding columns that I can pad the cells with a space character so the range looks good in an email?
EDIT: So this allows me to type in an email via an input box and select a range. It will create the email and send but it dosen't preserve the cell formatting (i.e spacing) Can this be done? I have tried using the MIME entities to use HTML however I'm not sure how I'd copy the range into the HTML body
Updated Code:
Sub Lotus_Email()
Dim noSession As Object, noDatabase As Object, noDocument As Object
Dim vaRecipient As String
Dim rnBody As Range
Dim Data As DataObject
Const stSubject As String = "EMAIL SUBJECT"
Const stMsg As String = "Please review the following Purchase Orders and advise."
Const stPrompt As String = "Please select the range:"
'This is one technique to send an e-mail to many recipients but for larger
'number of recipients it's more convenient to read the recipient-list from
'a range in the workbook.
vaRecipient = InputBox("Please enter an e-mail address", "E-Mail Address Entry")
On Error Resume Next
Set rnBody = Application.InputBox(Prompt:=stPrompt, _
Default:=Selection.Address, Type:=8)
'The user canceled the operation.
If rnBody Is Nothing Then Exit Sub
On Error GoTo 0
'Instantiate Lotus Notes COM's objects.
Set noSession = CreateObject("Notes.NotesSession")
Set noDatabase = noSession.GETDATABASE("", "")
'Make sure Lotus Notes is open and available.
If noDatabase.IsOpen = False Then noDatabase.OPENMAIL
'Create the document for the e-mail.
Set noDocument = noDatabase.CreateDocument
'Copy the selected range into memory.
rnBody.Copy
Set rtItem = noDocument.CreateRichTextItem("Body")
With rtItem
.appendtext ("LINE 1")
.addnewline (2)
.appendtext ("LINE 2")
.addnewline (2)
.addnewline (1)
.appendtext ("Please review and respond to the email noted above")
.appendtext ("TEST")
rnBody.PasteSpecial
End With
'Add data to the mainproperties of the e-mail's document.
With noDocument
.Form = "Memo"
.SendTo = vaRecipient
.Subject = stSubject
'Retrieve the data from the clipboard.
' NON-HTML BODY OFF
' .Body = stMsg & vbCrLf & vbCrLf & vbCrLf & vbCrLf & Data.GetText
.SaveMessageOnSend = True
End With
'Send the e-mail.
With noDocument
.PostedDate = Now()
.Send 0, vaRecipient
End With
'Release objects from memory.
Set noDocument = Nothing
Set noDatabase = Nothing
Set noSession = Nothing
'Activate Excel for the user.
AppActivate "Microsoft Excel"
'Empty the clipboard.
Application.CutCopyMode = False
MsgBox "The e-mail has successfully been created and distributed.", vbInformation
End Sub

UNTESTED. Maybe something like this?:
=A1&REPT(" ",25-LEN(A1))

So after using LotusNotes MIME I could import Rich Text, however it wouldn't preserve column width and excel formatting. I created a temp workbook with my range selection and attached it as an attachment. This seems to be the way to handle this with LotusNotes.

Related

Powerpoint SaveAs textbox form entry

Hello I have the following code written below to automatically send an email confirming that the user has filled out a form. Currently I have a powerpoint with one submit button which sends an automatic email. I also have a textbox named serial number where the user enters the part serial number.
I want to be able to send a copy of the filled out powerpoint form and have it named after the serial number. I am struggling to be able to save the textbox information as a variable. Does anyone know how to make the below functional. I apologize as I am fairly new to VBA.
Private Sub CommandButton1_Click()
Dim OL As Object
Dim EmailItem As Object
Dim Powerpoint As Presentation
Dim SerialNumtext As String
Dim FinalName As String
SerialNumtext = ActivePresentation.SelectContentControlsByTitle("SerialNumber")(1).Range.Text
FinalName = "Part Number" & SerialNumtext
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Powerpoint = ActivePresentation
Powerpoint.Save
With EmailItem
.Subject = "SUBJECT LINE"
.Body = "BODY MESSAGE" & vbCrLf & _
"SECOND LINE BODY MESSAGE" & vbCrLf & _
"THIRD LINE BODY MESSAGE"
.To = "enduseremail"
.Importance = olImportanceNormal
'send the email with the powerpoint named after the serial number
.Attachments.Add Powerpoint.FinalName
.Send
End With
Set Powerpoint = Nothing
Set OL = Nothing
Set EmailItem = Nothing
End Sub
Powerpoint doesn't have a SelectContentControlsByTitle method; instead, you'd access the control and its text like:
SerialNumtext = ActivePresentation.Slides(1).Shapes("SerialNumber").OLEFormat.Object.Text
This assumes the control is on Slide 1.
If you'd rather not make that assumption but can assume that the Submit button and text box are on the same slide:
SerialNumText = Me.Shapes("SerialNumber").OLEFormat.Object.Text
Me in this case returns a reference to the slide object that contains the control.

Code for checking to see if a new message with a specific subject line has been already created Lotus

I'm not a programmer so I apologize in advance.
I have three different worksheets in a workbook. Each sheet has a specific macro so that after numbers are entered, shift supervisors can press a button with the assigned macro and metrics from that sheet will be copied and pasted to a different worksheet in a format with filter-able/pivot-able columns. It then saves and closes the data, goes back to the shift report worksheet, copies the pertinent cells, then opens lotus and formats a new message with a subject line stating the correct shift number and date and pastes the shift report data into the body of the e-mail.
Since there is a different button to press on 3 worksheets, and I can't count on supervisors to enter numbers in any specific order, I need to be able to tell if Lotus has already opened and created an e-mail with that specific subject line to see if it needs to be created or if it exists with some information already in the body. Does anyone know if this is possible?
Dim NSession As Object
Dim NDatabase As Object
Dim NUIWorkSpace As Object
Dim NDoc As Object
Dim NUIdoc As Object
Dim WordApp As Object
Dim WordDoc As Object
Dim msg As String
msg = "Leads Report " & Now() & vbNewLine & vbNewLine & _
"Finishing:" & vbNewLine & _
"**PASTE Leadsheet CELLS HERE**" & vbNewLine & vbNewLine
Sheets("Leadsheet").Select
Set newRange = Range("e4")
mystring = RangeToString(newRange)
Set NSession = CreateObject("Notes.NotesSession")
Set NUIWorkSpace = CreateObject("Notes.NotesUIWorkspace")
Set NDatabase = NSession.GetDatabase("", "")
If Not NDatabase.IsOpen Then
NDatabase.OPENMAIL
End If
'Create a new document
'******************************(if statement to see
'if a document with specific subject line has already been
'created....'subject = doc.GetItemValue("subject")(0)???????
'****************************************
Set NDoc = NDatabase.createdocument
With NDoc
.SendTo = "email#email.com" 'CHANGE THIS
.CopyTo = ""
.Subject = Format(Date, "mm-dd-yyyy") & " Lead Report Shift " & mystring
'Email body text, including marker text which will be replaced by the Excel cells
.Body = msg
.Save True, False
End With
'Edit the just-created document to copy and paste the Excel cells into it
Set NUIdoc = NUIWorkSpace.editdocument(True, NDoc)
'Find the marker text in the Body item
'Replace it with the Excel cell
With NUIdoc
'leadsheet
Workbooks("Master Shift Report Sheet.xlsm").Activate
Sheets("LeadSheet").Select
Range("B2:o62").Select
ActiveWindow.zoom = 86
Selection.copy
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Add
With WordApp.Selection
.PasteSpecial DataType:=4 & vbNewLine
.wholestory
.copy
End With
.gotofield ("Body")
.findstring "**PASTE Leadsheet CELLS HERE**"
.Paste
'Application.CutCopyMode = False
'.Send
'.Close
End With
Set NSession = Nothing
anything else looks wonky don't hesitate to point it out! I'm learning.

How to ignore specific word from a group of words in a cell and send one email to group of people?

I am new to VBA. I am working hard and learning it but there is a point where I am stuck now. If someone please help me out then I shall be grateful.
I have a drop down list in excel like
Sales/Acquisition Manager (AM) Alina (Alina#yahoo.com)
Acquisition Project Manager (APM) Benny(Benny#yahoo.com)
Manufacturing Julia(Julia#yahoo.com)
Application please select (drop down list so I can choose)
AE external sensor responsible please select (Drop down list so I can choose)
I have made a separate row (row 59 Col A) where I have combined these values from the above rows.
I have to make a macro to send 1 email to these multiple people. I have written a code for sending email but I am stuck at another point. I have written code which replaces the words please select with “ ” whenever it finds it in row 59 but unfortunately that code changes the line permanently which I don’t want.
What I want is that whenever it finds the words please select in a row it just ignores it and and also doesn't change the format of cell. Means when I again change some new value by drop down list so it got changed.
Private Sub CommandButton1_Click()
Dim the_string As String
the_string = Sheets("Schedule_team").Range("A59")
the_string = Replace(the_string, "please select", " ")
Sheets("Schedule_team").Range("A59") = the_string
MsgBox (Sheets("Schedule_team").Range("A59"))
Dim i As Integer, Mail_Object, Email_Subject, o As Variant, lr As Long, x As Variant
Set Mail_Object = CreateObject("Outlook.Application")
x = Cells (59, 1).Value
With Mail_Object.CreateItem(o)
' .Subject = Range("B1").Value
.To = x
' .Body = Range("B2").Value
' .Send
.display 'disable display and enable send to send automatically
End With
MsgBox "E-mail successfully sent", 64
Application.DisplayAlerts = False
Set Mail_Object = Nothing
End Sub
Pull the contents of A59 into the string, replace as needed, then just use that string instead of copying it back to the sheet.
Untested, just used your code
Private Sub CommandButton1_Click()
Dim Mail_Object as Object
Dim the_string As String
the_string = Sheets("Schedule_team").Range("A59")
the_string = Replace(the_string, "please select", " ")
Set Mail_Object = CreateObject("Outlook.Application")
With Mail_Object.CreateItem(o)
' .Subject = Range("B1")
.To = the_string
' .Body = Range("B2")
' .Send
.Display 'disable display and enable send to send automatically
End With
MsgBox "E-mail successfully sent", 64
End Sub

Need correct macro coding to attach documents a/o files to Outlook from Excel Spreadsheet

I have a macro that searches a contact list that pulls data from a list of contacts in Excel, and prepares an email to be sent in Outlook.
Most of this macro works successfully. I am almost finished.
I also need it to search a folder (using the filename to be entered in cell A8) and attach the appropriate file to the emails.
(Folder path: C:\Users\SERGIL\Desktop\VATS )
Below is the code I have thus far:
Public Sub SendEmails()
Const cSUBJECT As String = "C2"
Const cBODY As String = "C3"
Const cSTART_ROW_INDEX As String = "C4"
Const cEND_ROW_INDEX As String = "C5"
Const cMAIL_TO_COLUMN As String = "G" ' The column with the email addresses in it
Const cCOMPANY_NAME_COLUMN As String = "B" ' The column with the Vendor/Company Names in it
'Put as many email addresses here as you want, just seperate them with a semicolon
Const cCC_EMAIL_ADDRESSES As String = "C6"
Const cFROM_ADDRESS As String = "C7"
Dim iRowCount As Integer
Dim iEndRow As Integer
'Grab the current open worksheet object
Dim oSheet As Worksheet
Set oSheet = ActiveSheet
iRowCount = oSheet.Range(cSTART_ROW_INDEX).Value2 ' Get the Start Value
iEndRow = oSheet.Range(cEND_ROW_INDEX).Value2 ' Get the End Value
Dim dBatchStart As Date
Dim dBatchEnd As Date
Dim sVendorName As String
Dim sEmail As String
Dim sSubject As String
Dim sBody As String
'Outlook must already be open, attach to the open instance
Dim oOutlook As Outlook.Application
Set oOutlook = GetObject(, "Outlook.Application")
'Declare a new draft email object
Dim oMail As Outlook.MailItem
'Start iterating through all the rows of mail, creating a new draft each loop
Do Until iRowCount = (iEndRow + 1)
'Actually instantiate the new draft email object
Set oMail = oOutlook.CreateItem(olMailItem)
'Display the draft on screen to the user can see and validate it
oMail.Display
'Set the TO address based on the data in the sheet
oMail.To = oSheet.Range(cMAIL_TO_COLUMN & iRowCount).Value2
'Get the subject, also, substitute the tags for Company and Start Date with the values in the sheet
sSubject = oSheet.Range(cSUBJECT).Value2
sSubject = Replace(sSubject, "<DATE FOR THAT VENDOR GROUP>", Format(dBatchStart, "Long Date"))
sSubject = Replace(sSubject, "<COMPANY>", oSheet.Range(cCOMPANY_NAME_COLUMN & iRowCount).Value2)
'Now insert the formatted subject into the draft email
oMail.Subject = sSubject
'Get the Body, substitute the tags for Start Date and End Date with the values in the sheet
sBody = oSheet.Range(cBODY).Value2
'Now insert the formatted Body into the draft email
oMail.HTMLBody = sBody
'Now add attachments
oMail.HTMLBody = sBody
'Set the CC address based on the Constant at the top
oMail.CC = oSheet.Range(cCC_EMAIL_ADDRESSES).Value2
oMail.Save
'Set the actual sender of the name. It won't display for the user, but will actually sent as that address
oMail.SentOnBehalfOfName = oSheet.Range(cFROM_ADDRESS).Value2
oMail.Save
'The draft mail item is now complete.
'The from address will need to be changed manually.
'The user will need to actually send the email once reviewed.
iRowCount = iRowCount + 1
Loop
With objMail
.Attachments.Add rngAttach.Value
.Display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
End With
End Sub
-- I am receiving an error with this segment of the code:
With objMail
.Attachments.Add rngAttach.Value
.Display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
The Add method of the Attachments class accepts four parameters. The Source parameter (the first one) should be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.
It seems you need to replace the rngAttach.Value statement with a valid parameter (a file or Outlook object).

Excel VBA Email Rows to a Single Recipient

I have a worksheet that tracks invoices and I am trying to generate an auto-emailer that if a cell in column 12 contains AUTOEMAIL it will combine all of the rows with a similar email address which I've generated using a TRIM function. It will pull all of the like rows (Email Addresses based on column 15) into a LotusNotes Email. Ron De Bruin has some fantastic examples on his site. I attempted to write a loop which attempts to loop through and copy all rows based on an email address. When I go to run, the code does nothing but no errors are presented. There are instances online of this done in Outlook, but they don't apply to LotusNotes as the issue is late vs early binding. I'm newer to VBA automation as well.
Sub Send_Data()
Dim noSession As Object, noDatabase As Object, noDocument As Object
Dim vaRecipient As Variant
Dim rnBody As Range
Dim Data As DataObject
Const stSubject As String = "TEST"
Const stMsg As String = "TEST"
Const stPrompt As String = "Please select the range:"
lastrow = Range("N" & Rows.Count).End(xlUp).row
For Each Cell In Range("N8:N" & lastrow)
If WorksheetFunction.CountIf(Range("N8:N" & Cell.row), Cell) = 1 Then
If Cells(Cell.row, 11) = "AUTOEMAIL" Then
rnBody = "Hello" & vbNewLine & vbNewLine & _
ActiveCell.EntireRow.Select
On Error Resume Next
'The user canceled the operation.
If rnBody Is Nothing Then Exit Sub
On Error GoTo 0
'Instantiate Lotus Notes COM's objects.
Set noSession = CreateObject("Notes.NotesSession")
Set noDatabase = noSession.GETDATABASE("", "")
'Make sure Lotus Notes is open and available.
If noDatabase.IsOpen = False Then noDatabase.OPENMAIL
'Create the document for the e-mail.
Set noDocument = noDatabase.CreateDocument
'Copy the selected range into memory.
rnBody.Copy
'Retrieve the data from then copied range.
Set Data = New DataObject
Data.GetFromClipboard
'Add data to the mainproperties of the e-mail's document.
With noDocument
.Form = "Memo"
.SendTo = vaRecipient
.Subject = stSubject
'Retrieve the data from the clipboard.
.Body = stMsg & " " & Data.GetText
.SaveMessageOnSend = True
End With
' SEND EMAIL
With noDocument
.PostedDate = Now()
.Send 0, vaRecipient
End With
' REMOVE FROM MEMORY
Set noDocument = Nothing
Set noDatabase = Nothing
Set noSession = Nothing
'SWITCH BACK TO EXCEL
AppActivate "Microsoft Excel"
'EMPTY COPY-PAST CLIPBOARD
Application.CutCopyMode = False
' DISPLAYS TO USER IF SUCCESSFUL
MsgBox "Complete!", vbInformation
End If
End If
Next Cell
End Sub
I set the email body range as a Prompt Box where the user could highlight the cells and then another prompt box in which it asked for the email that was created using a TRIM() function. I realized that the way the code was set-up would not allow for what I wanted to do. The new method works quite well
Treevar