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

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.