Using the Set Command to Your Advantage

Last week I created a post about the Windows path. A number of people wrote me about that post with questions. Yes, you can use the technique for setting the Path environment variable to set any other environment variable. The Windows Environment Variables dialog box works for any environment variable—including those used by language environments such as Java, JavaScript, and Python. Windows doesn’t actually care what sort of environment variable you create using the method that I discuss in that post. The environment variable will appear in every new command prompt window you create for either a single user or all users of a particular system, depending on how you create the environment variable.

A few of you took me to task for not mentioning the Set command. This particular command appears in both Administering Windows Server 2008 Server Core and Windows Command-Line Administration Instant Reference. It’s a useful command because you can temporarily configure a command prompt session to support a new set of settings. When the session is ended, the settings are gone. Only those settings you create as part of Environment Variables window have any permanence. There are other tricks you can use, but using Set for temporary environment variables and the Environment Variables window for permanent environment variables are the two most common approaches.

In order to see the current environment variables you simply type Set and press Enter at the command line. If you add a space and one or more letters, you see just the matching environment variables. For example, type Set U and press Enter to see all of the environment variables that begin with the letter U.

To set an environment variable, you add the name of the variable, an equals sign (=), and the variable value. For example, to set the value of MyVariable to Hello, you type Set MyVariable=Hello and press Enter. To verify that MyVariable does indeed equal Hello, you type Set MyVariable and press Enter. The command prompt will display the value of MyVariable. When you’re done using MyVariable, you can type Set MyVariable= and press Enter. Notice the addition of the equals sign. If you ask for the value of MyVariable again, the command prompt will tell you it doesn’t exist.

Newer versions of the command prompt provide some additional functionality. For example, you might set MyVariable within a batch file and not know what value it should contain when you create the batch file. In this case, you can prompt the user to provide a value using the /P command line switch. For example, if you type Set /P MyVariable=Type a value for my variable: and press Enter, you’ll see a prompt to enter the variable value.

It’s also possible to perform math with Set using the /A command line switch. There is a whole list of standard math notations you can use. Type Set /? and press Enter to see them all. If you write application code at all, you’ll recognize the standard symbols. For example, if you want to increment the value of a variable each time something happens, you can use the += operator. Type Set /A MyVariable+=1 and press Enter to see how this works. The first time you make the call, MyVariable will equal 1. However, on each succeeding call, the value will increment by 1 (for values of 2, 3, and so on).

Environment variables support expansion and you can see this work using the Echo command. For example, if you type Echo %MyVariable%, you see the value of MyVariable.

However, you might not want the entire value of MyVariable. Newer versions of the command prompt support substrings. The variable name is followed by a :~, the beginning position, a comma, and the ending position. For example, if you place Hello World in MyVariable, and then type Echo %MyVariable:~0,5% and press Enter, you see Hello as the output, not Hello World. Adding a negative sign causes the expansion to occur from the end of the string. For example, if you type Echo %MyVariable:~-5% and press Enter, you see World as the output.

The Set command is a valuable addition to both the administrator’s and programmer’s toolkit because it lets you set environment variables temporarily. The Set command figures prominently in batch file processing and also provides configuration options for specific needs. Let me know about your environment variable questions as they pertain to my books at


In Praise of Dual Monitors

A lot of people have claimed that the desktop system is dead—that people are only interested in using tablets and smartphones for computing. In fact, there is concern that the desktop might become a thing of the past. It’s true that my own efforts, such as HTML5 Programming with JavaScript for Dummies and CSS3 for Dummies, have started to focus on mobile development. However, I plan to continue using my desktop system when working because it’s a lot more practical and saves me considerable time. One such time saver is the use of dual monitors.

Yes, I know that some developers use more than just two monitors, but I find that two monitors work just fine. The first monitor is my work monitor—the monitor I use for actually typing code. The second monitor is my view monitor. When I run the application, the output appears on the second monitor so that I can see the result of changes I’ve made. Using two monitors lets me easily correlate the change in code to the changes in application design. Otherwise, I’d be wasting time switching between the application output and my IDE.

I also use two monitors when writing my books. The work monitor contains my word processor, while my view monitor contains the application I’m writing about. This is possibly one time when a third monitor could be helpful—one to hold the word processor, one to hold the IDE, and one to view the application output. However, in this case, a third monitor could actually slow things down because the time spent viewing the output of an example is small when compared to creating a production application.

The concept of separating work from the source of information used to perform the work isn’t new. People have used the idea for thousands of years, in fact. For example, when people employed typewriters to output printed text, the typist employed a special stand to hold the manuscript being typed. The idea of having a view of your work and then another surface to actually work on is used quite often throughout history because it’s a convenient way to perform tasks quickly. By employing dual monitors, I commonly get between a 15 percent to 33 percent increase in output, simply because I can see my work and its associated view at the same time.

Working with dual monitors not only saves time, but can also reduce errors. By typing as I view the output of applications, I can more reliably relate the text of labels and other information the application provides. The same holds true when viewing information sources found in other locations. Seeing the information as I type it is always less likely to produce errors.

Don’t get the idea that I support using dual monitors in every situation. Many consumer-oriented computer uses are served just fine with a single monitor. For example, there isn’t a good reason to use two monitors when viewing e-mail in many cases—at least, not at the consumer level (you could make a case for using dual monitors when working with e-mails and a calendar to manage tasks, for example). Dual monitors commonly see use in the business environment because people aren’t necessarily creating their own information source—the information comes from a variety of sources that the user must view in order to use reliably.

Do you see yourself using dual monitors? If you use such a setup now, how do you employ it? Let me know at


Choosing Variable Names

It often surprises me that developers seem to choose completely useless variable names like MyVariable when creating an application. Although MyVariable could be an interesting variable name for an example in a book, it never has a place in any sort of production code. Even then, I try to create book examples with meaningful variable names, especially when getting past the initial “Hello World” example. Variable names are important because they tell others:


  • What sort of information the variable stores
  • When the variable is commonly used
  • Where the variable is used
  • How to use the variable correctly
  • Why the variable is important

In some cases, the variable name could even indicate who created the variable; although, this sort of information is extremely rare. If you never thought a variable name should contain all that information, then perhaps you haven’t been choosing the best variable names for your application.

Even with these restrictions in place, choosing a variable name can be uncommonly hard if you want to maximize the name’s value to both yourself and other developers. Some organizations make the selection process easier by following certain conventions. For example, a form of Hungarian Notation, where certain type prefixes, suffixes, and other naming conventions are used, is a common way to reduce the complexity of creating a variable name. In fact, Hungarian Notation (or some form of it) is often used to name objects, methods, functions, classes, and other programming elements as well. For example, NamArCustomers could be an array of customer names (Nam for names, Ar for array). The use of these two prefixes would make it instantly apparent when the variable is being used incorrectly, such as assigning a list of numbers to the array. The point is that an organizational variable naming policy can reduce complexity, make the names easy to read for anyone, and reduces the time the developer spends choosing a name.


Before I get a ton of e-mail on the topic, yes, I know that many people view Hungarian notation as the worst possible way to name variables. They point out that it only really works with statically typed languages and that it doesn’t work at all for languages such as JavaScript. All that I’m really pointing out is that some sort of naming convention is helpful—whether you use something specific like Hungarian Notation is up to you.

Any variable name you create should convey the meaning of that variable to anyone. If you aren’t using some sort of pattern or policy to name the variables, then create a convention that helps you create the names in a consistent manner and document it. When you create a variable name, you need to consider these kinds of questions:


  1. What information does the variable contain (such as a list of names)?
  2. How is the variable used (such as locally or globally, or to contain coordinates, or a special kind of object)?
  3. When appropriate, what kind of information does the variable contain (such as a string or the coordinate of a pixel on screen)?
  4. Is the variable used for a special task (such as data conversion)?
  5. What case should prefixes, suffixes, and other naming elements appear in when a language is case sensitive?

The point is that you need to choose variable names with care so that you know what they mean later. Carefully chosen variable names make it possible for you to read your code with greater ease and locate bugs a lot faster. They also make it easier for others to understand your code and for you to remember what the code does months after you’ve written it. However, most important of all, useful variable names help you see immediately that a variable is being using the wrong way, such as assigning the length of a name string to a coordinate position on screen (even though both variables are integer values). Let me know your thoughts about variable naming at


Verifying Your Hand Typed Code

I maintain statistics for each of my books that are based on reviews and reader e-mails (so those e-mails you send really are important). These statistics help me write better books in the future and also help me determine the sorts of topics I need to address in my blog. It turns out that one of the most commonly asked questions is why a reader’s hand typed code doesn’t work. Some readers simply ask the question without giving me any details at all, which makes the question impossible to answer. In some cases, the reader sends the hand typed code, expecting that I’ll take time to troubleshoot it. However, this isn’t a realistic request because it defeats the very purpose behind typing the code by hand. If I take the time to diagnose the problems in the code you typed, I’ll be the one to learn an interesting lesson, not you. If you learn better by doing—that is, by typing the code by hand and then running it, then you need to be the one to troubleshoot any problems with the resulting code.

My advice to readers is to use the downloadable source code when working through the book text. If you want to type the code by hand after that as part of your learning experience, at least you’ll know that the example works on your system and you’ll also understand how the example works well enough to troubleshoot any errors in your own code. However, you need to be the one to diagnose the errors. If nothing else, perform a character-by-character comparison of your code to the example code that you downloaded from the publisher’s site. Often, a reader will write back after I suggest this approach and mention that they had no idea that a particular special symbol or method of formatting content was important. These are the sorts of lessons that this kind of exercise provide.

Now, it has happened that the downloadable source code doesn’t always work on a particular user’s system. When the error is in the code or something I can determine about the coding environment, you can be certain that I’ll post information about it on my blog. This should be the first place you look for such information. Simply click on the book title in question under the Technical category. You’ll find a list of posts for that book. Always feel free to contact me about a book-specific question. I want to be sure you have a good learning experience.

There are some situations where a reader tries to run application code that won’t work on a particular system. My books provide information on the kind of system you should use, but I can’t always determine exceptions to the rule in advance. When I post system requirements, your system must meet those requirements because the examples are guaranteed to fail on lesser systems. If you encounter a situation where the downloadable code won’t run on your system, but none of the fixes I post for that code work and your system does meet the requirements, then please feel free to contact me. There are times where an example simply won’t run because you can’t use the required software or the system won’t support it for whatever reason.

The point of this post is that you need to work with the downloadable source code whenever possible. The downloadable source code has been tested by a number of people, usually on a range of systems, to ensure it will work on your system too. I understand that typing the code by hand is an important and viable way to learn, but you should reserve this method as the second learning tier—used after you have tried the downloadable source code. Please let me know if you have any questions or concerns at


Application Development and BYOD

I read an article a while ago in InforWorld entitled, “The unintended consequences of forced BYOD.” The Bring Your Own Device (BYOD) phenomenon will only gain in strength because more people are using their mobile devices for everything they do and corporations are continually looking for ways to improve the bottom line. The push from both sides ensures that BYOD will become a reality. The article made me think quite hard about how developers who work in the BYOD environment will face new challenges that developers haven’t even had to consider in the past.

Of course, developers have always had to consider security. Trying to maintain a secure environment has always been a problem. The only truly secure application is one that has no connectivity to anything, including the user. Obviously, none of the applications out there are truly secure—the developer has always had to settle for something less than the ideal situation. At least devices in the past were firmly under IT control, but not with BYOD. Now the developer has to face the fact that the application will run on just about any device, anywhere, at any time, and in any environment. A user could be working on company secrets with a competitor looking right at the screen. Worse, how will developers legal requirements such as the Health Insurance Portability and Accountability Act (HIPAA)? Is the user now considered an independent vendor or is the company still on the hook for maintaining a secure environment? The legal system has yet to address these sorts of questions, but it will have to do so soon because you can expect that your doctor (and other health professionals) will use a mobile device to enter information as well.

Developers will also have to get used to working with new tools and techniques. Desktop development has meant working with tools designed for a specific platform. A developer would use something like C# to create a desktop application meant for use on any platform that supports the .NET Framework, which mainly meant working with Windows unless the company also decided to support .NET Framework alternatives such as Mono (an open source version of the .NET Framework). Modern applications will very likely need to work on any platform, which means writing server-based applications, browser-based applications, or a combination of the two in order to ensure the maximum number of people possible can interact with the application. The developer will have to get used to the idea that there is no way to test absolutely every platform that will use the application because the next platform hasn’t been delivered yet.

Speed also becomes a problem for developers. When working with a PC or laptop, a developer can rely on the client having a certain level of functionality. Now the application needs to work equally well with a smartphone that may not have enough processing power to do much. In order to ensure the application works acceptably, the developer needs to consider using browser-based programming techniques that will work equally well on every device, no matter what level of power the device possesses.

Some in industry have begun advocating that BYOD should also include Bring Your Own Software (BYOS). This would mean creating an environment where developers would make data available through something like a Web service that could be accessed by any sort of device using any capable piece of software. However, the details of such a setup have yet to be worked out, much less implemented. The interface would have to be nearly automatic with regard to connectivity. The browser-based application could do this, but only if the organization could at least ensure that everyone would be required to use a browser that met minimum standards.

My current books, HTML5 Programming with JavaScript for Dummies and CSS3 for Dummies both address the needs of developers who are looking to move from the desktop into the browser-based world of applications that work anywhere, any time. Let me know your thoughts about BYOD and BYOS at


The Place of Automation in the User Interface

There was a time that a developer could rely on users to possess a certain level of technical acumen. That’s no longer the case. Most of the people using a device containing a CPU today (I’m including PCs, laptops, tablets, and smartphones here) don’t know anything about how it works and they don’t care to know either. All these people know is that they really must have access to their app. (Some don’t even realize the role data plays in making the app work.) The app can perform myriad tasks—everything from keeping track of the calories they’ve eaten to maintaining the scheduled events for the day. Devices that contain CPUs have become the irreplaceable partner for many people and these devices must work without much concern on the part of the user. In short, the device must provide a superior level of automation or the user simply won’t know how to interact with it.

I was recently watching television and saw a commercial for a Weight Watchers app for mobile devices. In the commercial, a woman exclaims wonder about the new programs that Weight Watchers provides, which include this app for her mobile devices. To track her calories, she simply points her phone at the box containing whatever food she plans to eat and the app tracks the calories for her. The interesting part is that there is no data entry required. As technology continues to progress, you can expect to see more apps of this type. People really don’t want to know anything about your app, how it works, or the cool code you put into it. They want to use the app without thinking about it at all.

Of all the parts of a device that must be automated, the user interface is most important and also the most difficult to create. Users really don’t want to have to think about the interface. Their focus is on the task that the app performs for them. In fact, some e-mails I’ve received recently about my Windows 8 book have driven home the idea that the app must simply work without any thought at all. It’s because of these e-mails (and those for other books I’ve written) that I wrote the article entitled, “Designing Apps with Automation in Mind.” This article points out the essential behaviors that applications must exhibit today to be successful.

On the other side of the fence, I continue to encounter an “old world” philosophy on the part of developers that applications should pack as much as possible into a small space—users will eventually figure out the complexity of the interface provided. Unfortunately, as users become more vocal in requiring IT to meet their demands, these approaches to the user interface will lose out. The next app is a click away and if it does the job of automating the interface better, your app will lose out. Even if there isn’t another app to use, the user will simply ignore the app you’ve provided. The user will rely on an older version or simply not interact with the app if there is no older version. Many organizations have found out the hard way that attempting to force users to interact with an app is bound to fail.

The fact is, to be successful today, a developer must be part psychologist, part graphics artist, and part programming genius. Creating an acceptable interface is no longer good enough, especially when people want to access the same app from more than one device. The interface must be simple, must work well, and must automate as much of the input as possible for the user or it simply won’t succeed. Let me know your thoughts about user interface automation at


Installing and Managing Third Party Products

Most of my books make recommendations about third party products that you can use to enhance your computing experience. Each of these products is tested during the writing process, but without any of the add-on applications that may come with the product. For example, if I test a Windows enhancement product, I don’t test the toolbar that comes with that product. So, it’s important to realize that the advice you obtain in the book doesn’t include those add-on features.

However, it’s important to take a step back at this point and discuss why the product includes an add-on in the first place. Just like you, the product vendor has bills to pay and must obtain money from somewhere to pay them. An important concept to remember when working with computers is that free doesn’t exist. Typically, product vendors who offer free products will do so by paying for them in one of these ways:

  • Advertisements: Advertising comes in many forms, not just banner ads. Marketing types constantly come up with new ways to advertise products and induce you to buy them. A developer can obtain payment from advertisements in several ways, such as referral fees.
  • Product Add-ons: A developer can provide the means to install other products with the product that you’re installing. The company who provides the additional product sponsors the free product that you’re using.
  • Marketing Agreements: The application collects information about you and your system when you install it and the developer sells this information to marketing companies.
  • Value-added Products: The free product that you’re using is just a sample of some other product that the developer provides. If you like the free product, the developer is hoping that you’ll eventually purchase the full-fledged product.
  • Government Grants: A developer creates a product after obtaining a grant from the government. You pay for the product through your taxes.
  • Sponsorship: A larger company supports a developer’s work to determine whether the idea is marketable or simply the seed of something the larger company can develop later. You pay for the product through higher prices when you buy something from the larger company.

There are other methods that developers use to get paid for their work, but the bottom line is that they get paid. Whenever you see free, your mind should say, “This product doesn’t cost money, but there is some other price.” You need to decide whether you’re willing to pay the price the developer is asking. In the case of a government grant, you’ve already paid the price.

When you install a free product, you must watch the installation routine carefully. In almost every case, you must opt out of installing add-on products that the free product supports. So, you have to read every screen carefully because these opt-out check boxes are usually small and hard to see. The developer really isn’t pulling a fast one—just trying to earn a living. Make sure you clear any check boxes you see for installing add-on products if you don’t want that product on your machine. The reason I don’t discuss these check boxes in my books is that they change constantly. Even if I were to tell you about the check boxes that appeared at the time I installed the free product, your experience is bound to be different.

Of course, you might accidentally install one of these add-ons, an add-on that you really didn’t want. In this case, you must locate the product in the list of products installed on your system, such as the Programs and Features applet of the Control Panel for Windows users. The product name won’t be straightforward, but a little research will help you find it. Simply uninstall the add-on product. However, it’s always better to avoid installing something you don’t want to begin with, rather than remove it later, because few applications uninstall cleanly (even those from larger vendors such as Microsoft).

Unfortunately, there isn’t much I can do to help you when you install an add-on product. I do have some experience with the third party product in my book, but I won’t know anything about the add-on product. You need to contact the developer of the third party product to ask for advice in removing it from your system. This may seem like I’m passing the buck, but the truth is that the add-on products change all the time and there simply isn’t any way I can keep up with them all. When in doubt, don’t install a product, rather than being sorry you installed it later. Let me know your thoughts on third party products at


VBA and Office 2013 (Part 2)

I had posted some comments about using VBA with Office 2013 in my VBA and Office 2013 post. This post was based on the preview and not on the released product. Even so, most of the comments in that post still hold true. If you’re working with the desktop version of the product, you’ll find that most of the examples in VBA for Dummies will still work fine. However, the book is getting long in the tooth and the last version of Office that worked absolutely perfectly with the book was Office 2003. Since that release, Microsoft has made it progressively harder to use VBA as a viable development solution for the power user, hobbyist, and even the less skilled developer.

There are some new issues for Office 2013 that you need to know about. Most notably, it appears that some people can’t even access the Templates folder any longer without resorting to a kludge. By default, Office 2013 displays the templates and hides your personal templates, which should be a real productivity killer for the enterprise environment where custom templates reign. Yes, there is a fix for the problem (just click the links I’ve provided), but the issue is that you have to apply the fix to individual systems.

The fact of the matter is that Microsoft is making it abundantly clear that it would prefer that you not write applications for Office unless you’re willing to use Apps for Office. However, the process for creating an application in this manner is hardly as straightforward or as easy as using VBA. As far as I know, the template issue only affects one of the examples in Chapter 11. Please let me know if other chapters are affected by this issue (or any other Office 2013 issue for that matter). You can use the example in Chapter 11 after you apply the fix that is provided by Microsoft or third parties for regaining access to your personal templates.

Microsoft is also making a strong push for Office 365. This online version of Office can’t use VBA in any form. Even if you have your own templates and have carefully crafted VBA macros that would run with the desktop version of the product, you’re out of luck when it comes to Office 365. If you have this version of Office, you simply can’t use my book—attempting to do so is a waste of time.

You can continue to get full support for VBA for Dummies with desktop versions of Office, but may have to resort to some special changes as Microsoft makes Office less amenable to use with VBA. Please make sure you read the VBA for Dummies posts on my blog for updates and help with both Office 2007 and Office 2010 before contacting me.

Anyone who is attempting to write VBA macros for Office 2013 is in for a rough time and I’m sorry to see an era of personal productivity through VBA enhancement passing. If you own Office 2013 and contact me regarding VBA for Dummies, I’ll provide the best help that I can to you, but this support will be necessarily limited. Thank you for your continued support of my books. Perhaps I’ll eventually write an Apps for Office book to supplant VBA for Dummies. Please contact me with any concerns you have at


Interesting Additions to the Dummies Site

I’ve written a number of Dummies books over the years so I check on the Dummies site regularly to see what sorts of things the publisher is currently offering. Of course, there are always new books to read in a broad range of categories. Sometimes I like to browse just to see some of the interesting topics people have come up with over the years. For example, there is a book specifically for Yorkshire Terrier owners named, “Yorkshire Terriers for Dummies.” I keep hoping to find a Dummies book on Border Collies, but so far, no one has taken up the topic. Perhaps I’ll suggest such a book in the future since we work quite a bit with that particular breed. Keeping up with the wide range of books makes it a little easier for me to recommend books to my readers when they ask and I sometimes get a new idea or two simply by browsing through the topics pursued by others.

There are a couple new additions to the Dummies site that you might find interesting. First, if you really want a tee-shirt, coffee mug, or key chain (amongst other items) to show your love for Dummies products, you can get them at For Dummies Merchandise. I was a bit surprised to find that the site doesn’t offer hats at the moment, but perhaps that will change in the future.

Second, if you’ve ever wanted to create your own Dummies book, you can at least generate the cover now at The Official For Dummies Cover Generator. What you’ll get is a novelty cover that includes your title, bullet points, and art. Personally, I found some of the sample covers hysterical, so it’s worth a look even if you don’t intend to generate a cover. You’ll find titles such as Training Your Cat to Play Fetch for Dummies. Interestingly enough, our cat Smucker does, in fact, play fetch. So that particular cover caught my eye immediately.

The point behind these offerings is to have a bit fun with Dummies products. Even though the books cover serious topics, they’ve always done it is in a fun way, which is one of the reasons I’ve enjoyed writing for them so much. Let me know about your favorite Dummies site addition at


Displaying a Telephone Number in VBA

A number of readers of VBA for Dummies have now asked me how to insert a telephone number into documents using a macro. It turns out that this is a common topic online. Microsoft should have added this feature some time ago, but apparently hasn’t (and probably won’t at this point). Most of the solutions I’ve seen are complex when this really isn’t a complex task. This post discusses three techniques:


  • Insertion as text
  • Insertion in a field
  • Insertion in a control on the document.

Insertion as Text

The first approach is to insert the telephone number as text. You obtain unformatted input from some source, use the Format() function to format it, and then insert it at the current cursor location.

The first thing you need to do is gain access to the developer tools if you’re using Office 2010. The VBA in Office 2010 post tells you how to perform this task. Create a new module for your document or template using the instructions I’ve provided in the Adding a Module section in Chapter 3 of VBA for Dummies. At this point, you can create a new macro for inserting the telephone number. Here’s some simple code you can try.

Sub InsertTelephoneNumber1()
    ' Obtain the telephone number.
    Value = InputBox("Type the telephone number", "Telephone Number")
    ' Insert the telephone number directly.
    Selection.InsertAfter Format(Value, "(###) ###-####")
End Sub

The InputBox() call simply provides the means for obtaining a telephone number. You can use any source desired. The Selection.InsertAfter call inserts any text you provide after the current cursor location. The Format() function takes the input you received as the first argument (Value) and formats it using the picture you provide. You can find information about the Format function on MSDN at

Insertion as Field

The second approach is working with a field. It’s a little harder to create a field that contains a telephone number, but only slightly. Formula field codes are somewhat misunderstood and this particular example uses a trick that I haven’t seen others use online for some odd reason. This is one time when using the Macro Recorder will save you time. I discuss using the Macro Recorder in the Using the Macro Recorder section in Chapter 3 of VBA for Dummies. I used these steps in Office 2010 to create the example that follows later.


  1. Start the Macro Recorder. Call your macro InsertTelephoneNumber2 or anything else appropriate and add a comment.
  2. Choose Insert | Quick Parts | Field. You see the Field dialog box shown here.
  3. Select the = (Formula) option in the Field Names list and then click Formula. You see the Formula dialog box shown here.
  4. Type any ten digit number in the Formula field as shown.
  5. Type (###) ###’-‘#### in the Number Format field as shown. Notice especially the use the single quotes (‘) around the dash. This addition is where most people make their mistake in working with these formula fields. Any text you surround with a single quote like this is treated as text. Otherwise, the dash will simply disappear.
  6. Click OK. Word will add the field to the display. Notice that the field is formatted precisely as you’d expect, including the dash.
  7. Stop the Macro Recorder. Word will create the macro for you.

At this point, you have a macro that will insert a field containing a specific telephone number. To make the field more generic, you’ll need to modify the code to accept input. Here’s a simple version that you can try.

Sub InsertTelephoneNumber2()
    ' Obtain the telephone number.
    Value = InputBox("Type the telephone number", "Telephone Number")
    ' Use a field to display the telephone number.
    Selection.InsertFormula Formula:="=" + Value, NumberFormat:= _
        "(###) ###'-'####"
End Sub

Again, the code obtains a telephone number using an InputBox. You can use any source desired. It then calls Selection.InsertFormula with the content you want to use as the first argument and the format for that content as the second argument. Notice that that call relies on named arguments to avoid any potential problems. In addition, notice that the equals sign (=) is in double quotes (“), but that Value is outside of those double quotes because you want the value it contains, and not the word “Value” as input to InsertFormula.

Insertion as Control

The third technique is to create a control, allow the user to input the data, and then reformat the text in the control. Controls are different because they require a little better understanding of how Word works. When you have a control, it generates events. The event handler listens for those events and then does something about them. Think about a house fire. There is a fire in your home. So, you go out to the woods and yell, “There is a fire in my home!” Nothing happens. That’s because there is no handler in the woods for the event of a fire in your home. When you call 911, the 911 operator, the event handler, listens to you yell, “There is a fire in my home!” Now something happens. The 911 operator calls the fire trucks and sends them to your house to put out the fire.

It’s time to see how all of this works in the real world. I’m assuming that you’re using Word 2010 and that you have saved your document in .DOCM (document with macros) format. The following steps get you started.


  1. Choose Developer | Plain Text Content Control. You see a new Plain Text Content Control added to your document.
  2. Choose Developer | Properties. You see the Content Control Properties dialog box shown here.
  3. Type Telephone Number in the Title field and TN in the Tag field. Click OK. Word changes the properties of the Plain Text Content Control.
  4. Choose Developer | Visual Basic. You see the Visual Basic editor open.
  5. Right click the Project (<Document Name>)\Microsoft Word Objects\ThisDocument object in the Project Explorer window and choose View Code from the context menu. You see a module window open. (If you don’t see the Project Explorer window, choose View | Project Explorer to display it.)
  6. Select Document from the Object drop down list box in the module window (the one on the left). Word may automatically create an event handler for the New event. Remove this code because you don’t need it.
  7. Select ContentControlOnExit from the Procedure drop down list box in the module window (the one on the right). Word automatically creates the Document_ContentControlOnExit() event handler for you.

Now that you have an event handler, you have to tell it to do something. Just as the 911 operator needs to know what to do, so does Word. Here is an example of the code you could use to automatically format user input as a telephone number.

Private Sub Document_ContentControlOnExit( _
    ByVal ContentControl As ContentControl, _
    Cancel As Boolean)
    ' Verify the control's name.
    If ContentControl.Tag = "TN" Then
        ' Format the data in the control.
        ContentControl.Range.Text = _
        Format(ContentControl.Range.Text, "(###) ###-####")
    End If
End Sub

The Document_ContentControlOnExit() event handler receives two variables when Word calls it. The first contains all the information you need about the control that generated the event. The second lets you cancel the action when you detect a problem.

You only want to change controls that have a Tag value of TN. So, the first task is to detect controls of this type. The code then uses the ContentControl.Range.Text property to change the control’s text using the Format() function.

Bottom Line

These are three simple methods for adding a formatted telephone number to a Word document. However, you can extend these methods to format any sort of content. Just remember some of the rules you’ve learned here about working with formatted fields and then spend a little time with the Microsoft documentation to learn what else you can do. Please let me know if you have any questions about these techniques at