TweetFollow Us on Twitter

The REALbasic-Office secret decoder ring

Volume Number: 20 (2004)
Issue Number: 7
Column Tag: Programming

REALBasic Best Practice

by Guyren G Howe

The REALbasic-Office secret decoder ring

How to control Microsoft Office from REALbasic

Last time, I discussed some ways of "breaking out" of REALbasic, to call on external applications to supplement what your REALbasic application can do. I lamented that I was unable to explore controlling Microsoft Office from RB, because although it can do that really well, the documentation for this feature was both inadequate and horribly, egregiously wrong.

Since that time, things have gotten slightly better. There is now a web page (http://www.realsoftware.com/office2004mac/) from which you can download a small number of actual, correct, working examples. But, there is still no documentation to speak of, and what there is, it would lead you to believe that using Office from REALbasic is harder than it really is.

So in this article, I will present the apparently entirely undocumented, super-secret really easy way to control Office from RB.

But First...

Since I can't find anywhere else to put it, a quick aside: there were some errors in my article on REAL World. I had said I thought there were fifty attendees, but it turns out there were over a hundred. I also mistakenly wrote that there were three seminars per day, but what I meant to say was that there were three or four sessions at a time, and a bunch of sessions each day. It was quite a good seminar program.

Ta-Da! The Big Secret

Microsoft Office, on both Macintosh and Windows, incorporates a fairly sophisticated built-in scripting language called Visual Basic for Applications (VBA). The really super secret of controlling Microsoft Office from REALbasic -- the one I had to offer up my first-born and a handful of magic beans for -- is that REALbasic understands the entire VBA namespace. This means that essentially every term you can see in Word's object inspector (more on that in a moment) can be used in REALbasic. Classes from Word can be used in REALbasic just by sticking the letters Word in front of them (and similarly for Excel and PowerPoint), and method and function calls on those classes can (with one type of exception) be used unmodified. So, for example, you can fetch the text of the front most Word document with the following code:

GetTheFrontDocument()
A function that returns the text of the front most Word document
Sub GetTheFrontDocument() As String
dim w As New WordApplication
dim doc As WordDocument = w.ActiveDocument()
Return doc.Content().Text
End Sub

So the Word Document class becomes the WordDocument class in REALbasic. Also, the global methods and properties in VBA become method calls and properties on WordApplication, ExcelApplication, or PowerPointApplication in REALbasic.

There. The secret's out. Not much to it, really. Now I'll just fill in a few details, and explore some code examples.

Named Arguments

The only major difference between VBA and REALbasic is that VBA supports a nice feature called named arguments. This means that rather than having to remember, and write an ordered list of bare values for the arguments to a method call, you can provide them as assignment statements, like the last line of this code snippet (taken from the REALbasic built-in help for the Office class):

Example of Replace in VBA

Example Visual Basic for Applications code to perform a find and replace

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "find this"
.Replacement.Text = "replace with"
.Wrap = wdFindContinue
.Format = false
.MatchCase = false
.MatchWholeWord = false
.MatchWildcards = false
.MatchSoundsLike = false
.MatchAllWordForms = false
End With
Selection.Find.Execute Replace:=wdReplaceAll

This is great, but the translation into REALbasic, given in the built-in documentation, doesn't work. Here's how to actually do it:

The previous example, in REALbasic

Using the secret decoder ring, we translate the last example into REALbasic

Dim word as New WordApplication
Dim find As WordFind = word.ActiveDocument.Content.Find

find.ClearFormatting
find.Replacement.ClearFormatting
find.text = "find this"
find.Replacement.Text = "replace with"
find.Wrap = Office.wdFindContinue
find.Format = False
find.MatchCase = false
find.MatchWholeWord = false
find.MatchWildcards = false
find.MatchSoundsLike = false
find.MatchAllWordForms = false

// Now the fun stuff

Dim replaceParam as New OLEParameter
replaceParam.Value = Office.wdReplaceAll

// according to the docs on Find.Execute the Replace parameter is the 11th
replaceParam.Position = 11

find.Execute replaceParam

If you had more than one named parameter, you would use multiple OLEParameter objects, one for each named parameter, and you just pass them all, in any order, to the method call.

A Larger Example

I'm now going to go through a small, entirely artificial piece of code, intended to cram together a variety of techniques. This article is not remotely large enough to attempt even a quick survey of Office's impressive programming features, but I hope I've presented you with just enough to get you up, and going on your own.

The code will search through all the comments in the front most Word document. It will find all the comments that start with the word test followed by two numbers (all separated by spaces). Any such comment will be replaced by a table with the number of rows and columns given by the two numbers, and then the words "Hello, World" will be placed into the cell in the upper, left corner of the table. I'll go through not only the code, but more importantly how I worked out how to write it. I'll be working with Word X, not Word 2004. I don't consider the new version a worthwhile upgrade, so what you see will probably be slightly different in the newer version (although the code should still work the same).

Note that while the example, and my comments refer to Word, the same ideas apply to Excel and PowerPoint (except that, oddly enough, PowerPoint doesn't support macro recording).

Word's Macro Environment

Most of what you need to know, you can learn from within Word itself. In the Tools menu, you'll find a Macro submenu, which provides access to Word's programming features. In this menu, the REALbasic Editor command just launches REALbasic. The Record New Macro... command opens a dialog for you to name a new Macro, which is what Office calls a program written in VBA.


Figure SEQ Figure \* ARABIC 1: The Record Macro dialog

After you click OK in this dialog, you can execute a series of actions, and Word will translate those actions into a VBA program to do the same thing again. Note that you can't click to move the insertion point while you're recording a macro. There isn't any way for Word to turn that action, that only makes sense in that document (scrolling to that point, in a window of that size) into a set of actions repeatable anywhere.

While you're recording the macro, Word shows a tiny little window with stop and pause buttons:


Figure SEQ Figure \* ARABIC 2: The Macro recording palette

Now, just carry out the sorts of actions you want REALbasic to control, then hit the stop button in the little window. Next, go back to the Macro submenu and choose Macros.... You will then see a window showing the name of the macro you just recorded, along with any other macros you have previously written or recorded:


Figure SEQ Figure \* ARABIC 3: The Macros window

Click on the name of the macro you just recorded, then click Edit. Here is what I got when I recorded a macro in which I created a table along the lines of our little project:


Figure SEQ Figure \* ARABIC 4: The Word Macro editor

There are also other windows showing at this point, but describing this whole programming environment is outside the scope of this document, so I will stick to only what you need most for your REALbasic work.

The Object Browser

Recording a macro will generally give you a good idea of the kind of commands you need to execute to do something. You can also examine every available command, and class in Word by opening the Object Browser. You can do this by clicking a button on the toolbar you see in the macro editing environment:


Figure SEQ Figure \* ARABIC 5: The Object Browser button

Alternately, you can choose Object Browser from the View menu. Any of these will show Word's Object Browser:


Figure SEQ Figure \* ARABIC 6: The Word Object Browser

Note the search box in the middle, at the top (results appear in the blank area). The business part for our purposes is below the blank area. The list of Classes is comprehensive. <globals>, shown in the screen shot, are the methods, and properties available in the WordApplication class in REALbasic.

When you click on a class, the properties, methods, and constants are shown to the right of the class name. If you click on something shown there, its details are shown below, and it is all hyperlinked. This is actually how I developed the code for the example. Well, that, and examining the one working Word example that REAL Software has published.

There are some books on VBA (I understand the O'Reilly book -- ISBN 1-56592-358-8 -- is quite good), and a lot of material online. A bit of drill-down in the Object Browser, and some experimentation, gave me code to do my little example fairly easily.

The Example

To finish up, the example.

ReplaceCommentsWithTables

An example that finds comments in the front most Word document, replacing those that begin with the word table with a table whose dimensions depend on the rest of the comment

Sub ReplaceCommentsWithTables()
  Dim word as New WordApplication
  Dim c As WordComments
  c = word.ActiveDocument.Comments
  
  Dim counter As Integer
  Dim comment As WordComment
  Dim content() As String
  Dim width, height as Integer
  Dim location As WordRange
  if c.Count > 0 then
    counter = 1
    do
      comment = c.Item(counter)
      content = Split(comment.Range.Text(), " ")
      if content(0) = "table" then
        height = content(1).val
        width = content(2).val
        location = comment.Reference
        location.Tables.Add(comment.Reference, width, height)
        location.Tables.Item(1).Cell(1, 1).Range.Text = "hello, world"
      else
        counter = counter + 1
      end if
    loop until counter >= c.Count
  end if
End Sub

The only things that bear explaining here are that a Range in VBA is any point in the document, or any continuous section of text in the document. A Comment object has several Range properties. The one called Range is the actual content of the comment. The one called Reference is the location of the comment in the main text. Also, adding something (in this case, a table) to a range replaces the range's contents (in this case, the comment) with that table. Finally, collections of things in VBA will usually have an Item() function to fetch the collection's contents.

Apart from that, I hope you find that the mostly clear names for things in VBA, the ready availability of example code online, and the ability to record a macro if you want to know how to do something, will make this very useful feature of REALbasic surprisingly easy to use.

Brief aside: Just before I finished this, REAL Software announced a product called Office Power Pack, based on this feature in REALbasic. And Microsoft themselves have written some of the software that ships with Office (the installer and the query tool) in REALbasic. This is a practical feature indeed, and the market for Office add-ons or applications that can work with Office has to be substantial.

Finally, I will note that REALbasic's Office features are almost perfectly cross-platform, without modification other than to path strings and the like.


Guyren G Howe works in artificial intelligence research, after years of work as a technical write,r and developer. He is married with one child, is an Australian, and lives in Austin, Texas. Guyren has been working with REALbasic for several years. Most notably, he wrote the REALbasic Curriculum Project, an extensive computer science curriculum, for REAL Software (available from the REALbasic website). You can contact Mr. Howe at realbasic@mactech.com

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.