My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Monday, April 28, 2008

Internet Explorer Automation Object Library - Update for Excel 2007

One of the most popular pages on this site shows code for automating Internet Explorer. However I have only tested the code in Excel XP/2003. The purpose of this post is to credit a gentleman named Durand Sinclair who, using Excel 2007, pointed out to me that the name of the IE object library in Excel 2007 is actually called "Microsoft Browser Helper" (click Tools>References in the VBE). Once you select the checkbox, exit the dialog box and re-enter it, the name changes to "Microsoft Internet Controls".

If anyone else would like to verify this behavior in Excel 2007 and let me know, I would be grateful to hear it.

Thanks Durand!

--JP

Labels: , , ,


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Contribute to this site!

It's not what you think.

I'm asking for contributors to the VBA search engine!

If you know of a website with VBA samples, or think you have what it takes to identify good websites with code, I'd like to know about it.

Visit the VBA Search Engine Homepage and click "Volunteer to contribute". Send me a message (click here) and let me know you are going to do so.

You'll need a Google account to contribute to the search engine. An added bonus is you can add the search box to your Google homepage, so you can search whenever you want, and (if my eyes don't deceive me) you can also add the search engine code to your own blog or website!


Enjoy,
JP


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Sunday, April 27, 2008

Event Code for Forwarding Selected Text to Another Email Address

Here is the event code I promised for forwarding emails to another email address. It does exactly the same thing as the previous code, but since it is event code, once you place it in a class module and restart Outlook, it runs automatically without any need for you to run macros by hand.

Start by pasting the following into the ThisOutlookSession module:



Private WithEvents Items As Outlook.Items


Private Sub Application_Startup()
Dim objNS As Outlook.NameSpace
Set objNS = GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder _
(olFolderInbox).Items
End Sub


This code will set up the event handler. If you already have an Application_Startup event, simply copy and paste the inner code into it. Of course you'll want to check that you aren't duplicating any code; Option Explicit and a quick Debug>Compile will check for that.

The ItemAdd event will check any newly added items to the Inbox, and, if they meet the criteria we specify, a new mail item is created (via the Forward method) and sent to the email address of our choice. Then the original message is marked as read and neatly tucked away. Here is the complete code:



Private WithEvents Items As Outlook.Items


Private Sub Application_Startup()
Dim objNS As Outlook.NameSpace
Set objNS = GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder _
(olFolderInbox).Items
End Sub


Private Sub Items_ItemAdd(ByVal item As Object)

If item.Class = olMail Then
If Left$(item.Subject, 16) = _
"String to search" Then
Dim Msg As Outlook.MailItem
Dim NewForward As Outlook.MailItem
Dim MyFolder As Outlook.MAPIFolder
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace

Set Msg = item
Set NewForward = Msg.Forward
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set MyFolder = olNS.GetDefaultFolder _
(olFolderInbox).Folders("Archive")

With NewForward
.Subject = _
Right(Msg.Subject, Len(Msg.Subject) _
- InStrRev(Msg.Subject, " "))
.To = "myemail@mobiledevice.com"
.HTMLBody = ""
.Send
End With

With Msg
.UnRead = False
.FlagStatus = olNoFlag
.Move MyFolder
End With
End If
End If

ExitProc:
Set NewForward = Nothing
Set Msg = Nothing
Set olApp = Nothing
Set olNS = Nothing
Set MyFolder = Nothing
End Sub


Paste this into the ThisOutlookSession module, save and restart Outlook to get the code to start working.

I chose some arbitrary criteria (the first 16 characters of the Subject Line), you would need to customize this for your needs.

Labels: , ,


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Saturday, April 26, 2008

Custom CSS tags for displaying well-formed VBA code

So you might be wondering, what does VBA have to do with a web technology like CSS? If you are like me and you hand-code your website, you might find it difficult to display VBA code properly. Unfortunately, I can't seem to locate a copy of zHTML, and the other VBA-to-HTML converters I tried just don't seem to satisfy.

Since my website is formatted using CSS, I did a bit of digging and found I could create my own HTML tags. I was already using the PRE and TEXTAREA tags to format snippets of VBA code, but this technique allows you to create custom tags that make it simple to roll your own webpages. So I went ahead and wrote some CSS to format the four most commonly posted types of VBA code: Normal, Selection, Comment and Keyword Text. Here it is:

.vba
{ color: #000000;
background: #FFFFFF;
padding: 10px 10px 10px 10px;
font-size: 100%
}
.selected
{ color: #FFFFFF;
background: #330099;
}
.comment
{ color: #339933;
background: #FFFFFF;
}
.keyword
{ color: #330099;
background: #FFFFFF;
}

Paste the above code into the .css file that defines your site's layout. You can fiddle with the background color to make it suit your site better. Now you can wrap your VBA code in tags like this:

<pre class="vba">
<span class="keyword">Sub</span> fixformulas()
<span class="comment">'
' if you have some formulas with a ' or some other
' character in the beginning
'</span>
<span class="keyword">Dim</span> cell
<span class="keyword">As</span> Excel.Range
<span class="keyword">For Each</span> cell
<span class="keyword">In </span> Selection
cell = "=" & Right(cell, Len(cell) - 1)
<span class="keyword">Next</span> cell
<span class="keyword">End Sub</span>
</pre>


And it will display like this:


Sub fixformulas()
'
' if you have some formulas with a ' or some other
' character in the beginning
'

Dim cell As Excel.Range
For Each cell In Selection
cell = "=" & Right(cell, Len(cell) - 1)
Next cell
End Sub



The PRE tag wraps the area in the "vba" tag, which is the default black-on-white
text used to display most VBA code (if you haven't fiddled with the default settings in the VBE). So any code that isn't wrapped in a span tag will automatically take on the default color, which is the intuitive way the VBE does it.

Instead of using the deprecated FONT tags or trying to guess the hex values for colors every time you want to use them, you can use friendly words like "keyword" or "comment" in your SPAN tags and the code will be colored accordingly. The PRE tag will also make sure the code is indented properly!

Eventually I'll convert all the existing code to this format, and all future code posted on the blog and the website will be displayed using these custom made CSS class tags.

(ps- the Outlook event code I promised last week is coming up in the next day or two. I was away this week so I have a lot of catching up to do.)


Enjoy,
JP

Labels: , ,


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Wednesday, April 16, 2008

Forwarding Selected Text to Another Email Address

Greetings,

I would like to share some code I wrote last month for a user who visited my website and asked for a macro that would look for specific text in the subject of an email and forward it to another email address (in this case, an email for a mobile device). I created two versions: a Sub procedure that could be run on demand, and Event code that would automatically (in the "hands off" spirit) forward a specially crafted email.

In this post I will show the macro you would assign to a toolbar button. If you want to add this (or any other) macro to your Outlook toolbar, check out "How to assign a macro to a toolbar button" on this page. In the next post I will follow up with the Event code.

The toolbar code should be placed in a standard module in your Outlook VB Project.


First we check what type of window we are looking at by checking the ActiveWindow Property of the Application object; if it is an Explorer, that means we don't have any emails open, so we set an object reference to the first selected item. If it is an Inspector, we have an email or other item open for viewing, so we set an object reference to it. Of course, if there is no selected item, or no open item, the code fails with an error because we can't run it.



Sub FwdMailText()
Dim objItem As Object
Dim Msg As Outlook.MailItem
Dim NewForward As Outlook.MailItem
Dim MyFolder As Outlook.MAPIFolder
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace

On Error Resume Next
Select Case TypeName(Application.ActiveWindow)
Case "Explorer"
Set objItem = _
Application.ActiveExplorer.Selection.item(1)
Case "Inspector"
Set objItem = _
Application.ActiveInspector.CurrentItem
End Select
On Error GoTo 0

If objItem Is Nothing Then
MsgBox "Nothing selected!", _
vbExclamation
Goto ExitProc
End If




If we made it this far, we check if our object reference is to a MailItem
by checking the Class Property for the olMail constant. If it is indeed a MailItem, we set a friendly object reference "Msg" to it. I like to use string variables that easily identify what the variable represents; similar to Hungarian notation. That way I can spend more time worrying about what the code should do and less time guessing what each variable does every time I look at it. Fortunately, "Msg" is one of those non-reserved keywords that make it obvious.


If objItem.Class = olMail Then
Set Msg = objItem
Else
MsgBox "No message selected!", _
vbExclamation
GoTo ExitProc
End If

Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set MyFolder = olNS.GetDefaultFolder(olFolderInbox)._
Folders("Archive")


At this point we execute the Forward Method of the MailItem object,
which creates a new email message based on the original, and returns an object reference to the about-to-be-forwarded MailItem. We set up the Subject: and To: fields, and use the Subject: from the original MailItem to create the Body of the forwarded item.

After sending the message, we move the original email to the folder called "Archive" which is one level below the default Inbox (see object reference for "MyFolder").


Set NewForward = Msg.Forward
With NewForward
.Subject = "Information You Requested"
.To = "myemail@mobiledevice.com"
.Body = Right(Msg.Subject, _
Len(Msg.Subject) - InStrRev(Msg.Subject, " "))
.Send
End With

With Msg
.UnRead = False
.FlagStatus = olNoFlag
.Move MyFolder
End With

ExitProc:
Set NewForward = Nothing
Set Msg = Nothing
Set objItem = Nothing
End Sub


Here is the code in its entirety:


Sub FwdMailText()
Dim objItem As Object
Dim Msg As Outlook.MailItem
Dim NewForward As Outlook.MailItem
Dim MyFolder As Outlook.MAPIFolder
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace


On Error Resume Next
Select Case TypeName(Application.ActiveWindow)
Case "Explorer"
Set objItem = _
Application.ActiveExplorer.Selection.item(1)
Case "Inspector"
Set objItem = _
Application.ActiveInspector.CurrentItem
End Select
On Error GoTo 0


If objItem Is Nothing Then
MsgBox "Nothing selected!", _
vbExclamation
Goto ExitProc
End If


If objItem.Class = olMail Then
Set Msg = objItem
Else
MsgBox "No message selected!", _
vbExclamation
GoTo ExitProc
End If


Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set MyFolder = olNS.GetDefaultFolder(olFolderInbox)._

Folders("Archive")
Set NewForward = Msg.Forward


With NewForward
.Subject = "Information You Requested"
.To = "
myemail@mobiledevice.com"
.Body = Right(Msg.Subject, _
Len(Msg.Subject) - InStrRev(Msg.Subject, " "))
.Send
End With


With Msg
.UnRead = False
.FlagStatus = olNoFlag
.Move MyFolder
End With


ExitProc:
Set NewForward = Nothing
Set Msg = Nothing
Set objItem = Nothing
End Sub



For the Body property, I chose to include the text from the subject line (everything starting from the left all the way up to the first space) of the original item, but you can include anything you want. If you wanted to include the original message body in the forward, try this:



.Body = Msg.Body

If you are curious about the properties and methods of the MailItem object, you can enter a new line right below "With NewForward" and type a period "." You should get a dropdown list of everything you can do with a MailItem, courtesy of Intellisense. Once you select one, you can press F1 for assistance and sample code. This is a great way to learn about the properties of an object; just declare an object of a specific type, then start typing "objectname." and you get that list. Just be sure you go to the Options in the VB Editor in Outlook (press Alt-F11, then go to Tools>Options) and on the Editor tab, check all the boxes in the "Code Settings" frame.

Enjoy,

JP

Labels: , , ,


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Monday, April 14, 2008

Hands Off That Email Attachment!

About halfway down the Outlook page, there is some VBA code for opening an Excel workbook attached to an email, running a macro on it, then cleaning up and moving the email to another folder.

Here is some more sample code to make your macro even more intelligent. This code opens the attachment, then scans through the spreadsheet looking for an error condition. If the error condition is met, an email is generated to another mailbox, as an alert, and the email is left in the Inbox to be looked at by a human. If the error condition isn't met, there's no reason to look at the email, so it gets marked as read and moved to an archive folder.

If you are like me, then your time is valuable. You don't want to spend time looking at emails that you don't need to work on. This code lets me focus on high-value activities while using Outlook's built-in capabilities to ignore the spreadsheets that don't need personal attention.

First you want to open ThisOutlookSession and paste this event code:

Private WithEvents QueueInbox As Outlook.Items
Dim bWasPosted As Boolean


Really you can use anything in place of "QueueInbox", but I use something that will relate to the task so I can easily identify what the code is doing. The boolean variable is put in the global section because we are using it in one procedure (the mail sending sub) and checking the value in another sub.

Now you need to tell Outlook to monitor your chosen Inbox for new items. This code placed in the Application_Startup event will do that.


Set QueueInbox = objNS.Folders("Mailbox - My Mailbox Name").Folders("Inbox").Items


Replace "My Mailbox Name" with the name of the mailbox you want to check. For example, if I were running this on my own Inbox, the code would be


Set QueueInbox = objNS.Folders("Mailbox - Jimmy Pena").Folders("Inbox").Items


If you don't have an Application_Startup event, just put "Private Sub Application_Startup()" right above the Set statement, and "End Sub" right below it.

Now on to the real work. When a new item is added to the Inbox we selected, it saves and opens the attachment, checks to make sure everything is OK, and if so, moves the email to an archive folder. Don't forget to set a reference to the Excel object library (see binding page for assistance).

Of course I make some assumptions here, which you might want to change. For example, the emails we are checking have a known sender and subject, which was pre-arranged. Also, they always have one .xls attachment. If you can agree on a system like this, you'll be able to use Outlook code to automate some pretty boring processes.


Private Sub QueueInbox_ItemAdd(ByVal Item As Object)

Dim objNS As Outlook.NameSpace
Dim ArchiveFolder As Outlook.MAPIFolder
Dim Msg As Outlook.MailItem
Dim myAttachments As Outlook.Attachments
Const attPath As String = "C:\"
Dim colACount As Long
Dim colGCount As Long
Dim cell As Excel.Range
Dim MyBook As Excel.Workbook
Dim MySheet As Excel.Worksheet
Dim colARange As Excel.Range
Dim colGRange As Excel.Range
Dim bBadCount As Boolean

bWasPosted = False
bBadCount = False

Set objNS = GetNamespace("MAPI")

' the archive folder we are moving emails to
Set ArchiveFolder = objNS.Folders("Mailbox - My Mailbox Name")._

Folders("Inbox").Folders("Archive")

' check to make sure we are looking at a mailitem
If TypeOf Item Is Outlook.MailItem Then
If (Item.SenderName = "MySender@somewhere.com") And _

(Item.Subject = "Attachment You Requested") Then
' obj ref to msg
Set Msg = Item
' get attachment
Set myAttachments = Msg.Attachments
Att = myAttachments.Item(1).DisplayName
myAttachments.Item(1).SaveAsFile attPath & Att

' open workbook and check for errors
Set XLApp = New Excel.Application
Set MyBook = XLApp.Workbooks.Open(attPath & Att)
Set MySheet = MyBook.Sheets(1)


' check count of columns A & G to make sure they match

' at this point you could do anything you want to the workbook, as if you
' were in the Excel VBE
Set colARange = MySheet.Range("A2:A5000")
Set colGRange = MySheet.Range("G2:G5000")

colACount = colARange.SpecialCells(xlCellTypeConstants).Count
colGCount = colGRange.SpecialCells(xlCellTypeConstants).Count

If colACount <> colGCount Then

' we found an error!
MyBook.Close False

' call other macro and pass email to it as an argument,
' so we can use some properties of the current mailitem
Call PostMsg(Msg)
bBadCount = True
End If

' bBadCount is a boolean variable checking if the match count
' caused an error, we skip further checks if that is the case
' because we only need one error

If bBadCount = False Then
' the count matched, but maybe we have invalid values
For Each cell In colGRange.SpecialCells(xlCellTypeConstants, 2)
If (cell.Value = "#N/A") Then
MyBook.Close False
Call PostMsg(Msg)
End If
Next cell
End If

' at this point, if PostMsg was called,
' bWasPosted would be True

If bWasPosted = False Then
' we didn't post a msg to MyInbox, so there must be
' nothing wrong with the attachment, so we can move it
With Msg
.UnRead = False
.Move ArchiveFolder
End With
End If
End If
End If

ExitProc:
On Error Resume Next
XLApp.DisplayAlerts = False
XLApp.Workbooks.Close
XLApp.DisplayAlerts = True
Kill attPath & Att
XLApp.Quit
On Error GoTo 0
Set ArchiveFolder = Nothing
Set objNS = Nothing

End Sub


Sub PostMsg(Msg As Outlook.MailItem)
'
' sub that actually puts the email in the inbox
'

Dim NotifyMsg As Outlook.MailItem
Dim MyFolder As Outlook.MAPIFolder
Dim objNS As Outlook.NameSpace
Dim strMsg As String

Set objNS = GetNamespace("MAPI")
Set MyFolder = objNS.Folders("Mailbox - Jimmy Pena").Folders("Inbox")

Set NotifyMsg = MyFolder.Items.Add(olMailItem)

With NotifyMsg
.Subject = "Invalid Attachment Received"
.Importance = olImportanceHigh
.To = "jpena@myemail.com"
strMsg = "The following message was received by Queue Inbox on " & Msg.ReceivedTime & ":"
strMsg = strMsg & vbCr & vbCr & Msg.Body
strMsg = strMsg & vbCr & vbCr & "This is an automatically generated message."
.Body = strMsg
.UnRead = True
End With

bWasPosted = True

NotifyMsg.Send

End Sub



After implementing this code, you'll see that it checks incoming mail items for the ones with the appropriate sender and subject, browses through the attachment for errors, and sends an email to your Inbox of choice if an error is found. If no error is found, it quietly marks the email as read and moves it to another folder.

Now, hands off!

Enjoy,
JP

Labels: , , ,


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Tuesday, April 8, 2008

Updated blog and new pages

As you may have noticed, I decided to update the blog, because it was getting hard to navigate. The color scheme was just bringing me down, so I spent about 4-5 hours changing it. That might seem like a lot of time, but I'm a perfectionist so once I start working I don't stop until it's perfect. I guess it's just the programmer in me.

Speaking of which, I added two new pages to the site: one with a great circle distance UDF and another with some samples for using the varType() function.

I am also working on a set of Outlook macros/event code to use as a file put/request system. Once added to your Outlook, other people would send you emails with a specially formatted subject; your system would respond by sending the requested file as an attachment, or putting the received attachments into the folder specified by the sender.


Enjoy,
JP


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Monday, April 7, 2008

UDF to return page headers/footers text

Here's a series of short UDFs that will return the page headers and footers for the active worksheet.


Function GetLeftHeader()
GetLeftHeader = ActiveSheet.PageSetup.LeftHeader
End Function


Function GetCenterHeader()
GetCenterHeader = ActiveSheet.PageSetup.CenterHeader
End Function


Function GetRightHeader()
GetRightHeader = ActiveSheet.PageSetup.RightHeader
End Function


Function GetLeftFooter()
GetLeftFooter = ActiveSheet.PageSetup.LeftFooter
End Function


Function GetCenterFooter()
GetCenterFooter = ActiveSheet.PageSetup.CenterFooter
End Function


Function GetRightFooter()
GetRightFooter = ActiveSheet.PageSetup.RightFooter
End Function

To use: Just put the function name in the cell, prefixed by an equal sign. For example, to get the left header text in cell A1:

=GetLeftHeader()

If you use any of these functions in a workbook other than the one where the code resides (ex: your PERSONAL.XLS workbook), you may have to prefix the code like this:


=PERSONAL.XLS!GetLeftHeader()

You can also use them in VBA code to get the associated property and take appropriate action, for example:

Sub TestMe()
Dim strMyHeader As String

strMyHeader = GetLeftHeader

If strMyHeader <> "My Company Name" Then
ActiveSheet.PageSetup.LeftHeader = "Company Name"
Else
MsgBox strMyHeader & " is your company's name."
End If

End Sub



HTH,

JP


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Rows to Repeat at Top

If you want to programmatically set the "Rows to Repeat At Top" option on the Sheet tab in Excel's Page Setup dialog box, here are two ways to do it.

If you already know what range you want, you could use this code:

ActiveSheet.PageSetup.PrintTitleRows = "$1:$1"

This would set row 1 (which would ideally be a list of column headers) to print at the top of every page.

To set this option based on a user selection:

ActiveSheet.PageSetup.PrintTitleRows = Selection.Areas(1).Address

This code assumes that you have selected at least one entire row, i.e. select rows 1 through 4 then use the code above to set "Rows to repeat at top" to $1:$4.


HTH,
JP

Labels: , ,


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Friday, April 4, 2008

Excel User Conference

I was browsing Jon Peltier's blog and found a link to the Excel User Conference. It being held in Atlantic City which is only a couple hours' drive from my house, so I will be attending. And as soon as I save the money to pay the attendance fees, I'll be able to say that with 100% confidence.

If you are in the area and are reading this blog, you should try to attend. Check out the link to the conference to see the topics and presenters.


Enjoy,
JP


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Thursday, April 3, 2008

Training class update

The Advanced Excel class tutorial is almost finished. I still have to write the section on 'Macros'. I'm considering just cutting and pasting from the web, because I'm not sure I have the strength to write something from the ground up. Or it might just be a brief introduction with some simple examples -- you can't teach macro writing in a 3 hour class. I've been writing them semi-regularly for the last three years and only in the last three months have I been doing it on an almost daily basis.

Speaking of which, some of the code I wrote way back then is atrocious, but it got the job done. Even to this day it is still being used in my organization and saves countless man-hours of tedious manual work.

Like I said a few months ago, I will post the sample workbooks and the written tutorial once it's done. I'm not a technical writer, but I like the way it seems to be coming together. I had to figure out how to sync up the workbooks with the written text to make it all flow together like course material should. Not easy! But I think I managed to pull it off, and it's definitely reusable if anyone wants to re-use it.


Keep thinking,
JP


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Tuesday, April 1, 2008

Quickly Clear Conditional Formatting

Here is a simple sub that deletes conditional formatting from a selection. The code does some prelim checking to see that it is actually acting on a range, and it mimics Excel's usual behavior (like a good VBA procedure should, if I may say so) by acting on the entire worksheet if you only select a single cell. However I recommend just selecting the range before you run the code.

Sub Clear_Cond_Formatting()
Dim rng As Excel.Range

If TypeName(Selection) <> "Range" Then Exit Sub
If TypeName(Selection.Parent) = "Chart" Then Exit Sub
If TypeName(Selection.Parent.Parent) = "Chart" Then Exit Sub

Select Case Selection.Cells.count
Case 1
Set rng = Cells
Case Else
Set rng = Selection
End Select

On Error Resume Next
rng.FormatConditions.Delete
On Error GoTo 0
End Sub



Enjoy,
JP

Labels: , , ,


Digg It! Stumble It! del.icio.us Technorati

My blog has moved! Visit Code For Excel And Outlook Blog and update your bookmarks.

Simple Word macro/button to print out a form

Happy April Fool's Day!

Here is a simple macro in MS Word that you can use to print out a document to the default printer.
  • Go to View>Toolbars>Control Toolbox to display the Control Toolbox.
  • Click the "Command Button" icon to insert a command button in your document. You can drag it anywhere you like and resize as needed.
  • Double click the button to view the code window. You should be taken right inside an auto-created Click event that looks like this:

Private Sub CommandButton1_Click()

End Sub

  • Paste the following code in between those lines:

ActiveDocument.PrintOut

  • Press F4 to view the Properties window for the command button and change the "Caption" property to something like "Print" or something else useful.
  • Press Alt-Q to close the VB Editor and return to MS Word.
  • On the Control Toolbox, click "Exit Design Mode". You can close the toolbar if you wish.

Test it out by pressing the button! It will send your document to the default printer. Keep in mind the button is displayed on the document so it will be printed as well.

Enjoy,

JP


Digg It! Stumble It! del.icio.us Technorati