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
Related
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.
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.
So I am currently studying SQL Server but right now I am just working a standard office admin job while I'm studying.
I never really made macro's before and little knowledge on VB but decided to design a macro for work to make things a bit easier for my team.
The macro just very simply allows the user to enter data, stats etc and gives the percentage or average statistic resulting in a total letting the user know if the statistics have been hit that day, week, month etc.
It works well but I would like to add a "SUBMIT" button that when a user clicked it would send the data they have entered in specified cells to myself. I am not sure how to go about it, If needed I don't have access to systems like SQL, Visual Studio etc in work as said just basic admin job at the moment.
Would It need to be submitted as a CSV? or could it be submitted from the user's sheet straight onto another macro I have designed giving the results for the whole team? As said I am totally new to this idea.
Cheers Guys.
Awright, according to what you may need in a very simple approach, the first thing you need to do it's to know the cells where they're going to enter info (care with ranges ), let's assume for this example that whe only had one data entered in the first cell of the team worksheet. So, create a button called 'button1' or as you wish and on the click event use this code :
Private Sub button1_click()
Teamsheet.Cells(row,column) = Yoursheet.Cells(destinyrow,destinycolumn)
End Sub
That would copy the value from one sheet to another, now, if you had you sheet locked via password, you must unlock it before doing that,then lock it again so code would be like this :
Private Sub button1_click()
On Error Resume Next
yoursheet.unprotect password:="yourpassword"
Teamsheet.Cells(row,column) = Yoursheet.Cells(destinyrow,destinycolumn)
On Error Resume Next
yoursheet.PROTECT password:="yourpassword"
End Sub
I clarify that this is a very simple approach, so, if you're using specific cells you can copy one by one and this would do (so you can make anny calculation son your admin sheet), but when you're copying ranges should be like this :
Teamsheet.Range("A1:D3").Value = yoursheet.Range("A1:D3").Value
Also, always consider how they enter this data you need.
UPDATE :
Let's say you have a team workbook and yours is admin_workbook, concept it's similar. This code will do what you need but both workbooks should be at the same folder or path :
Private Sub button1_click()
Var_data = Teamsheet.Cells(row,column)
Application.ScreenUpdating = False
Workbooks.Open Filename:=ThisWorkbook.Path & "\admin_workbook.xls"
ThisWorkbook.Activate
Admin_sheet.Cells(destinyrow,destinycolumn) = var_data
Workbooks("admin_workbook.xls").Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub
First you capture data on a var, then you open your admin book, put the data on the cell you want and close that workbook saving changes (you decide if you keep this line or mantain the workbook open and save manually). Also, Application.screenupdating it's a line that helps your screen doesn't flick when changing between workbooks.
Hope it helps friend !
I have very little experience of VBA or macros as will, no doubt, become self-evident. I have got to the point that I can create the email perfectly if I am in the worksheet that holds all the information. As soon as I step out of that Worksheet then I start to get issues. I have tried changing the ActiveWorkbook.EnvelopeVisible = True line to refer to the pertinent worksheet but am failing. I have tinkered for a while and tried a few permutations and am struggling to understand what I need to do.
Help (please)!
Ideally I would like to have the workbook only show the worksheets that the users need to see; this means hiding & protecting the worksheets that have the formula to identify the correct email address(es), subject (various concatenated componants) and the range of cells (formatted and spaced as set out in the worksheet) for the body (as body html or rtf rather than an attachment). So on buton click an email is created and sent (with user told this has happened).
We have Office 2010 with Outlook in use.
I have adapted the script from http://support.microsoft.com/kb/816644 to the below:
Sub MArefEmail()
' MArefEmail Macro
' Create email to provide the referral for the service
' Select the range of cells on the active worksheet.
Worksheets("Referrals").Range("P93:AB113").Select
' Show the envelope on the ActiveWorkbook.
ActiveWorkbook.EnvelopeVisible = True
' Set the optional introduction field thats adds
' some header text to the email body. It also sets
' the To and Subject lines. Finally the message
' is sent.
With Worksheets("Referrals").MailEnvelope
.Introduction = "Referral requested by applicant during pre-tenancy interview."
.Item.To = "service#xxx.org.uk"
.Item.CC = "first.last#xxx.org.uk"
.Item.Subject = Range("b43").Text
'.Item.Send
End With
MsgBox "Referral email sent to yyy service"
End Sub
All help welcome.
Background
I have been building an income/expediture calculator with a benefit's assessment, bill estimators and a number fo flags and notifications built in for a Housing Association aimed to help support low-income families. It also has calculations to identify (if pertinent) any loss of benefits income due to recent Welfare Reform - both local and national benefits - and savings. The organisation has properties across over 100 local authorities each with their own rules.
It is used by front line staff (some technophobic) with the applicant ususally in front of them.
The workbook also identifies people that meet certain criteria to flag the offer of a referral to services that might help (e.g. Employment & Training support). There are six different services, each of which has a number of providers and restrictions, some location-based. The referral currently works by flagging that the applicant has met the criteria (to be likely to benefit from the service) and suggests the applicant is offered the service. If the applicant says "Yes" then a concatenated hyperlink clicked that prefills the To, Cc & Subject fields depending on the location, service, household make-up and property type. The Subject also includes the timeframe for the referral (as give to the customer).
Each subject is bespoke. The bespoke subject is used by the people recieving the referral to identify priorities while in the inbox without having to review the body of the email; the bespoke subject is set up to allow sorting as per the referral agency's requirements (i.e. each one is different!).
The member of staff then needs to move to another worksheet to copy and paste a range of cells into the body of the email. Each of the six referral types has a different range of cells and then send the email. This process ensures the quality of information required for each referral.
Speed is a key driver for improvements to the "tool". I am at the point of trying to find waste steps and speed improvements. Automating the email could save up to 2 minutes per interview and reduce the chance of errors.
You need to hide certain worksheeets as I understand it.
the worksheets are part of a collection in the workbook.
You can either iterate through them by index:
dim iIndx as integer
For iindx=1 to worksheets.count
if worksheets(iindx).name<>"Referrals" then
worksheets(iindx).visible=xlSheetHidden
else
worksheets(iindx).visible=xlSheetVisible
end if
next
or by member
dim oSheet as worksheet
for each osheet in worksheets
if osheet.name<>"Referrals" then
osheet.visible=.Visible=xlSheetHidden
else
osheet.visible=.Visible=xlSheetVisible
end if
next
so you can just hide all the other sheets prior to making the Envelope visible, and unhide them later.
HTH
Philip
Actually, I'm not a beginner. I know nothing about them, though I do have some programming background.
This is the thing: I have a couple of Word documents and an Excel spreadsheets. The documents need to grab some data from the spreadsheet and then print. There needs to be one document per spreadsheet row, and they need to be printed all together.
I'm not asking for code or anything; I just want to know what's the right tool for the job, and if someone could point me to a tutorial or reference or something.
This is for Office 2003 (or XP, I'm not sure).
EDIT: It seems like there are many ways to do this, so it'd be great if someone listed the pros and cons of each solution. Keep in mind that it's something that will be done many times, and once programmed/recorded/whatever it should be easy to use for someone who is not a programmer.
Javier,
Couldn't find a good tutorial, but something like this should help you get going:
You can enable the developer toolbar, if it's not available from Word options. Then, click on the Visual Basic button and add a procedure or function that can be called from your document or a command button in the Word UI.
Sample showing some super basic Excel integration:
Public Function GetValue()
Dim myExcel As Excel.Application
Dim myWorkbook As Excel.Workbook
Dim myWorkSheet As Excel.Worksheet
Set myExcel = CreateObject("Excel.Application")
Set myWorkbook = myExcel.Workbooks.Open("c:\temp\myworkbook.xlsx")
Set myWorkSheet = myWorkbook.Worksheets(1)
Dim cellValue As String
cellValue = myWorkSheet.Cells(1, 1).Value
GetValue = cellValue
End Function
This will require you add a reference to Excel object library (type library) from the Excel developer IDE.
You can load your Excel spreadsheets via VBA in an ADODB and read the ADODB row by row.
How To Use ADO with Excel Data from Visual Basic or VBA
You can accomplish this with the built-in mail merge facility in Word. There's a walkthrough of how to use it in Word 2003 here
edit: further to the question in the comments, once you have set up the mail merge document, you can save it complete with its link to the data source. This means that when the document is opened again the user just needs to say "Yes" to the choice of data being merged.
The user can (independently) also choose to have the mail merge toolbar displayed. Clicking on the "Merge to new document" button on the Mail Merge toolbar would cause the merged letters to be generated. If the toolbar isn't displayed then they need to go Tools > Letters and Mailings > Mail Merge and use the wizard to complete the job