Using outlook VBA to trigger an Excel Macro to read email content - excel

I have wrote a outlook Macro to call an excel Macro to read the target email content and write it to excel sheet.
target email come in --> excel Macro run and search email in outlook --> read content into excel
The issue I have is that excel macro can run successfully if it is trigger manually on excel. when the Macro is trigger through outlook VBA, excel Macro can only read the email content upto row 251.
Can anyone help me or suggest a way to debug?
In outlook, I tried to trigger excel macro like below:
'Debug.Print "Opening excel file"
Set Wb = XlAPP.Workbooks.Open(File)
Set Ws = Wb.Sheets("Read Me")
Ws.Activate
'Debug.Print "Run Macro"
Wb.Application.Wait (Now + TimeValue("0:00:05"))
Wb.Application.Run "Module1.getDataFromOutlook"
In excel, I check how many rows in the email content like below:
'split email content into rows
Content = item.Body
'Application.Wait (Now + TimeValue("0:00:05"))
Debug.Print Len(Content)
Lines = Split(Content, vbCrLf)
My excel Macro Debug print result is attached in below screenshot.
Thanks in advance for your help!

The Outlook object model doesn't provide any limitations when dealing with message bodies. See Excel specifications and limits for more information on Excel limits.
The Outlook object model provides three main ways for working with item bodies:
Body.
HTMLBody.
The Word editor. The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body.
See Chapter 17: Working with Item Bodies for more information.
It is not clear from your lines of code published there why there is a difference there. You need to publish the full code from the getDataFromOutlook sub to get any valuable feedback.

Related

Collecting more than one data from Clipboard

I manually copy 4 or 5 pieces of text from an email body to clipboard.
Then I want a procedure that assigns each one of these piece of text to a string variable separated by semicolons.
The “codes” below do not work. I write them just to helping explain what I want.
I will appreciate any help.
Sub ColectClipboardItems()
Dim strClip As String
strClip = vbNullString
For Each Item In Clipboard.Items
strClip = strClip & ";" & Item
Next Item
End Sub
I'm not sure if it's true, but the following link indicates that currently Excel can only handle information from the Windows clipboard, which only stores one value at a time:
Access The Nth Item of Clipboard
However, you could try to create the following:
Two step manual process:
A macro in Outlook that stores your data in the Windows clipboard (concatenated). Instead of Ctrl + C you would click a button in your Outlook ribbon.
A macro in Excel that retrieves such data from it.
I think this is prone to human errors.
Or a one step process:
A macro in Outlook that stores all your data & by itself calls another macro in Excel to save it there.
This depends on your e-mail having a consistent structure, though.

Replacing text in an email with a picture from the clipboard

I have a report that I send out daily.
In it there is a linked image to a range that I need to paste into an email and send.
I have the email saved as an outlook template file that I modify as necessary when I need to.
The code I have runs from Excel.
I create an Outlook object and open the Outlook email from the .oft template file, then I want to find the identifier text (INSERT IMAGE HERE) and replace it with the linked image from Excel, which has been copied from the clipboard.
I am trying to add it as an InLineShape so that it behaves properly in the body of the email.
I have been attempting to do it with a defined WordEditor from the body of the email.
I looked into HTML to do it, but I decided the WordEditor object would be a better approach.
After I paste it, I need to set the scale height to 0.75 so that it is displayed properly.
From there, just click send.
Here is a quick sample of my code:
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookEmail = OutlookApp.CreateItemFromTemplate(templatePath)
OutlookEmail.Display 'Just for code checking
ThisWorkbook.Worksheets("Email Sheet").Pictures("Summary Email Screenshot").Copy
Set EmailText = OutlookEmail.GetInspector.WordEditor
With EmailText.Range.Find
.ClearFormatting
.Execute findText:="*INSERT IMAGE HERE*", MatchWholeWord:=True, MatchCase:=True, _
MatchWildcards:=False, ReplaceWith:="^c", Replace:=wdReplaceOne
End With
EmailText.InlineShapes(EmailText.InlineShapes.count).ScaleHeight = 75
'OutlookEmail.Send
The problem arises with that last line before I send it.
What happens is it is not inserted as an InLineShape, but just a shape so that it floats on top of the text.
I need it as an InLineShape so that the content after the image moves down and is displayed rather than being covered by it.
I've been scowering forums for a while to try to find an answer but to no avail.
I am pretty well versed in Excel VBA, but this is my first attempt at Outlook and Word VBA so please, bear with me.
By default when an image is pasted Word will use the setting Insert/paste pictures as from File/Options/Advanced, section "Cut, copy and paste". So on some machines an image might be pasted as an InlineShape and on others as a Shape.
If you were simply pasting in the code then using PasteSpecial it would be possible to specify inline or with text wrap using the corresponding WdOLEPlacement enumeration value of either wdFloatOverText or wdInLine.
Since the paste command is coming from the ^c replacement text this approach won't work for this situation. That means the Options setting will need to be changed. And, in order for this to be user-friendly, at the end of the code it should be changed back.
Here's some sample code demonstrating how to check the current option, change it if necessary, and reset at the end of the procedure. I'm not familiar with using Word through the Outlook object model, but I think I've correctly instantiated an object for the Word.Application so that VBA executing in Excel or Outlook will know what Options are meant. Except for the last line, this should come between Set and With in the code sample in the question.
Dim wrapType As Long
Dim wordApp as Object
Set wordApp = EMailText.Application
wrapType = wordApp.Options.PictureWrapType
If wrapType <> wdWrapMergeInline Then
wordApp.Options.PictureWrapType = wdWrapMergeInline
End If
'Do other things, then reset
wordApp.Options.PictureWrapType = wrapType

Macro to save documents generated with word/excel automatically

At this moment, I have a document where you enter several output from other programs, this data is converted into some statistics and graphs per person depending on who you select in a combobox (form control). this works fine at this moment.
The excel is connected to a MS Word document which displays the graphs and statistics from the person selected in the excel document.
I would like to have a button that automatically saves the individual document as PDF with a different name.
manual: open both documents
manual: click on the macro
macro: go to first of the combobox list (this can be done by changing output of combobox to 1)
loop
macro: open word and safe as pdf
macro: if number of people that have to be done is same as output combobox, end
macro: go to the next of the list (change output combobox by +1)
end loop
I have tried it for a long time but cannot manage it, I would be very thankful if somebody could help!
I use office 2010
To save a document as PDF you just need to run this line
objWordDocument.SaveAs "C:\TEMP\Doc1.pdf", 17
The complete code to a button sabe a opened Word document is below.
Sub SaveWordAsPDF()
Dim wordObj
Dim objWordDocument As Object
Set wordObj = GetObject(, "Word.Application")
Set objWordDocument = wordObj.Documents(1) '1 is the reference index to the documente, if there are more than 1 opened you need to see wich one is the one you want
objWordDocument.SaveAs "C:\TEMP\Doc1.pdf", 17
End Sub

Extract data out from currently viewed Email via Excel VBA

I am new in Excel VBA and still trying hard to understand Excel VBA.
Am trying to make life easier for my team members.
Appreciate if someone can point me a direction on how to retrieve out text from the currently viewed email and paste the information on a Excel speadsheet.
Email will look something like this.
Name: Tan AK
Contact number: 65-12223456
=====================================
Would like to extract out the details
E.g
Cell A1 should display the first sentence
Cell A2 should display the second sentence.
Appreciate if someone can help me out.
General questions like yours are not popular here. Below I give information that should get you started. If you run into difficulties try a question like this:
I want to achieve A but the half-a-dozen statements below do B. I do not see what I am doing wrong.
Questions which focus on a single issue and demonstrate what you have tried are usually answered very quickly.
The Outlook security system makes it much more difficult for an Excel macro to read from Outlook than for an Outlook macro to write to Excel.
On the other hand, it is much easier to distribute an Excel macro because you can email the workbook to each of your friends and they can immediately use it. With an Outlook macro, you will have to export the module and each friend would then have to import it.
I suggest you start with an Outlook macro. When you have learnt enough to get that macro working to your satisfaction, you may know enough to start exploring the issues of reading from Outlook .
This little Outlook macro show how to access the selected emails:
Option Explicit
Public Sub DemoExplorer()
Dim Exp As Outlook.Explorer
Dim ItemCrnt As MailItem
Dim NumSelected As Long
Set Exp = Outlook.Application.ActiveExplorer
NumSelected = Exp.Selection.Count
If NumSelected = 0 Then
Debug.Print "No emails selected"
Else
For Each ItemCrnt In Exp.Selection
With ItemCrnt
Debug.Print "From " & .SenderName & " Subject " & .Subject
End With
Next
End If
End Sub
The Outlook macro in the answer below creates an Excel workbook and exports details of every email in the Inbox to it. This demonstrates many of the techniques you will need. Perhaps more importantly, it shows what the text and html bodies of an email look like to a VBA macro. This will help you split a body into sentences.
How to copy Outlook mail message into excel using VBA or Macros

Call Excel VBA from Word

We have a standard form in MS Word to manually fill in details and launch a macro. This macro will open a MS Excel register to auto populate it from the fields in the Word document whilst doing other things.
The current solution has a keyboard shortcut for the macro in the Excel spreadsheet and the Word document macro sends the keys strokes to the opened Excel spreadsheet to launch the macro. This only works for a few people in the office.
Can I call my Excel macro directly from the Word macro while my Excel spreadsheet is in focus or is there a Windows setting that is blocking my send keys to launch the macro?
This is just a hunch, but would it be possible to migrate the Excel macro from the Excel spreadsheet to the Word document? Then you could add a bit of code to launch the correct Excel spreadsheet and perform the necessary field manipulations. So, basically, let your Word document do all the work on the Excel spreadsheet.
Alternately, you could follow the procedure discussed here:
http://support.microsoft.com/kb/177760
Here is the relevant code listing:
Sub XLTest()
Dim XL as Object
Set XL = CreateObject("Excel.Application")
XL.Workbooks.Open "C:\My Documents\ExcelFile.xls"
' If there is more than one macro called TestMacro,
' the module name would be required as in
'
' XL.Run "Module1.TestMacro"
'
' to differentiate which routine is being called.
'
XL.Run "TestMacro"
End Sub

Resources