Click here to Skip to main content
Click here to Skip to main content

A little known trick to help with MS Office automation

By , 2 Dec 2005
 

Introduction

Have you ever wondered how to do Microsoft Office automation? Do you have some experience with Word or Excel or some other product, but you just can’t seem to program it to do what you want? Well, I discovered a neat little trick, which I am going to share with you, that has often helped me figure out how to do Office automation.

Background

What is Microsoft Office automation? It is the process of using OLE and COM object hooks into the Microsoft Office suite in your programming code. Why would you want to do this? I have found that often there is a need to do something or display something and it would be really handy if we could just use MS Office behind the scenes to do it. Perhaps you want some custom output in Word or Excel format. In many cases, you can use some reporting tool that will export to RTF or Excel. Still, sometimes the output you are trying to create is unique enough that you need to program it with MS Office automation.

The most recent thing I have done with MS Office automation was I used Word to add a page footer with a field that had the current date time stamp on it. My application was already using Word to print RTF documents. The RTFs were created using Crystal Reports. The users wanted a printed date on the RTF. The only way I could think of doing it was using Word Automation.

The Trick

One word: Macros. I know it sounds too easy. I found, a few years ago, when I was doing some Excel automation in a Delphi app, that I could not find any good reference on the web or a book that would help me figure out what I wanted to do. Anyway, I finally figured out that if I started to record a macro in Excel (this works in Word etc.) and did whatever I was trying to do in automation, I found that the macro code was always very close to the code I needed to write in automation to get the same results.

An Example

Here is how you start a macro in word:

Starting a Macro in Word

Next, we will insert a date into the header while the macro is recording.

Insert DateTime in Header

Next, we stop the macro and look at the code it created. Click on Tools > Macro > Macros and this window comes up:

Edit the Macro code

Select the macro you just recorded and click Edit.

The Macro code

You do have to know what code you are looking for. This is the macro code we are interested in:

ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldDate

The C# code looks like this:

wordApp.ActiveWindow.ActivePane.View.SeekView = 
Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;

wordApp.Selection.Fields.Add(wordApp.Selection.Range,
ref fieldtype, ref datetime, ref isFalse);

You can see how similar the code is to the macro code. Here is the full source to add the current date-time to a Word document:

// give any file name of your choice. 
object fileName = "c:\\temp\\test.doc"; 
object  read_only  = false;
object  visible  = true;
object  isFalse    = false;

//provide a date format for the date we are inserting.
object  datetime = @"DATE \@ ""yyyy/MM/dd hh:mm:ss""";
object  fieldtype = 
Microsoft.Office.Interop.Word.WdFieldType.wdFieldDate;

//  the way to handle parameters you don't care about in .NET 
object missing = System.Reflection.Missing.Value; 

//   Open the document that was chosen by the dialog 
Microsoft.Office.Interop.Word.ApplicationClass wordApp = 
new Microsoft.Office.Interop.Word.ApplicationClass();

wordApp.Visible = false;

Microsoft.Office.Interop.Word.Document aDoc = 
wordApp.Documents.Open( 
    ref fileName, ref missing, ref read_only, 
    ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref visible, ref missing, 
        ref missing, ref missing, ref missing );

try
{
    wordApp.ActiveWindow.ActivePane.View.SeekView = 
      Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;

    wordApp.Selection.Fields.Add(wordApp.Selection.Range,
ref fieldtype, ref datetime, ref isFalse);
    aDoc.Save();
                
}
finally
{
    aDoc.Close(ref isFalse, ref missing, ref missing);
    wordApp.Quit(ref isFalse,ref missing,ref missing);
}

Conclusion

So I suggest if you find yourself in need of using MS Office automation and you are just not sure how to do what you need to do, record a macro while you are doing it and then look at the macro code. There is a good chance that the macro code will point you in the right direction for the code you need to write.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

kubben
Web Developer
United States United States
Member
I started my programmer career over 16 years ago doing COBOL and SAS on a MVS mainframe. It didn't take long for me to move into windows programming. I started my windows programming in Delphi (Pascal) with a Microsoft SQL server back end. I started working with vb.net when the beta 2 came out in 2001. After spending most of my programming life as a windows programmer I started to check out asp.net in 2004. I achieved my MCSD.net in April 2005. I have done a lot of MS SQL database stuff. I have a lot of experience with Window Service and Web services as well. I spent three years as a consultant programing in C#. I really enjoyed it and found the switch between vb.net and C# to be mostly syntax. In my current position I am programming in both vb.net and C#. Lately I have been using VS2012 and writing a Windows 8 app. You can search for the app it is called ConvertIT.
 
On a personal note I am a born again Christian, if anyone has any questions about what it means to have a right relationship with God or if you have questions about who Jesus Christ is, send me an e-mail. ben.kubicek[at]netzero[dot]com You need to replace the [at] with @ and [dot] with . for the email to work. My relationship with God gives purpose and meaning to my life.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralYou saved my baconmembersgharp22 Oct '09 - 9:54 
I know this is a rather old article but it just saved me from several days of torture.
 
Thanks very much....
GeneralRe: You saved my baconmemberkubben22 Oct '09 - 11:05 
I am glad the article helped you out.
 
Ben
General2 issues on your articlememberBobCarp9 Jun '09 - 8:14 
Your article is great and I have been able to successfully build reports
 
However I have 2 glitches.
1. Whitespace is translated to spaces. How do I preserve whitespace in using this process?
 
2. Ho do I spawn WinWord to print the document and then close. Like right clicking on a Doc file and selecting print on pop up menu
 
thank you for your help
GeneralRe: 2 issues on your articlememberkubben9 Jun '09 - 17:07 
You know I don't know how to keep the white space from getting translated to spaces.
If you want winword to print your doc like when your right click a doc file, you have to figure out the paramters to winword. I don't remember exactly what they are, but I am sure a quick google search will lead to do the correct answer. It is something like
winword /print docname
I don't remember for sure.
 
Ben
GeneralNice! ThanksmemberPHinker2 May '09 - 1:55 
This is a great trick especially for those of us just starting out with automation! Thanks very much for this article.
GeneralRe: Nice! Thanksmemberkubben2 May '09 - 1:57 
Glad you liked the article. Before I figured this out I was trying to search everywhere to try and figure out how to do stuff. It is much easier to just have the macro write the code for you.
 
Ben
GeneralRe: Nice! ThanksmemberPHinker2 May '09 - 4:26 
Yes, I had been banging my head a couple days trying to figure out how to do something programmatically. Using your method I was able to sort it out in 10 minutes!
GeneralRe: Nice! Thanksmemberkubben2 May '09 - 9:11 
That is great! I am glad to hear it.
 
Ben
QuestionRecord macro In C#memberMember 41487886 Nov '08 - 22:23 
Hi
who I Can Open OfficeWord By C# and start to record a macro and save It??
AnswerRe: Record macro In C#memberkubben7 Nov '08 - 0:20 
You know I haven't actually tried to save a macro, usually I just try to use the macro to see what the code would look like in C#. Then I put the macro code into C# and it does what I want in word. I am not sure how that would work anyway, since starting to record a macro takes user input like mouse clicks and keystrokes. So then your C# app would have to do all of that while you are recording a macro.
 
Now by chance you are asking how do you start and record a macro in word.
In office 2003 or later you go to tools -> macros -> record macro
 
In office 2007 click on the view tab then macros then record macro.
 
Sorry I can't me more help.
 
Ben
GeneralRe: Record macro In C#memberMember 41487887 Nov '08 - 2:00 
tanks
I know that =>> any work can run in word by C# that is (Macroable) and change VB Macro To C# for example " Selection.TypeText Text:="Hello" -OR- ShowVisualBasicEditor = True " To
{word.Selection.TypeText("Hello"); -AND- word.ShowVisualBasicEditor = true; } In C#. But the question is ( what is function Of Record macro In VB to translate in C# )
very thanks AND BYE
GeneralRe: Record macro In C#memberkubben7 Nov '08 - 2:15 
I am still not totally sure I understand your question. I think you want to start recording a word macro in C#. I have never done that and I don't know if it can be done. If you include a refrence to the office ddl in your project the intellsense should work on the word object. So you can search through the different methods exposed in the word object and see if a start macro method exists.
 
Sorry I can't help more.
Ben
GeneralRe: Record macro In C#memberSREHMANISLD13 Oct '11 - 19:30 
i want to built macro application for all general activities by visual studio in vb.net if any one have some material please share with me.
QuestionHow to end the table in the word document automationmemberMember 418197531 Mar '08 - 17:49 
i have created the table in the word, now i want to add the picture below the table.But with my code the picture is added in one of the column of table.Now i want that how to end the table.
AnswerRe: How to end the table in the word document automationmemberkubben1 Apr '08 - 1:47 
I would guess that you need to add a return key so that word knows you are on the next line not in the table. That is my guess.
 
Ben
QuestionHow can we create a word document with footer on each page and the text in footer is like pages X of YmemberMember 418197530 Mar '08 - 20:59 
How can we create a word document with footer on each page and the text in footer is like pages X of Y.
AnswerRe: How can we create a word document with footer on each page and the text in footer is like pages X of Ymemberkubben31 Mar '08 - 1:11 
Well, if you follow what my article talked about. First you turn on the record for the word macro. Then you turn on the page N of N in word. Then you look at the macro to see what the macro code looks like. Then you look at the word automation object in .net and the code should be pretty close to what you see in the macro.
 
Hope that helps.
Ben
GeneralRe: How can we create a word document with footer on each page and the text in footer is like pages X of YmemberMember 418197531 Mar '08 - 17:45 
Thanks a lot i have got the solution...
 
sunil rajak
GeneralRe: How can we create a word document with footer on each page and the text in footer is like pages X of Ymemberkubben1 Apr '08 - 1:45 
I am glad you figured it out. Nice job!
 
Ben
QuestionHow can we add field to a table cell placed in header section.memberQasim Raza6 Apr '07 - 7:06 
HI,
 
In my scenario i need to add a field in the a table cell that is placed in the header Section of page.
 
Field that i am trying to insert is Page X of Y ( X is the current page number and Y is the total number of pages in document)
 
The code you have written replaces the whole header. Can you any body tell me how to add field in the header section table.
 
thanks,
Qasim
AnswerRe: How can we add field to a table cell placed in header section.memberkubben6 Apr '07 - 8:26 
I suggest that you create a macro while you are doing they above code and then look at the macro code. That should give you a pretty good idea how to do it.
 
Hope that helps.
Ben
GeneralAvoid POP upsmemberIamADotNetGuy10 Aug '06 - 3:09 
Hi
 
we are trying to automate office @ server side with specific user account(dcom service configured to run under specific user account who is a local administrator) and this is recommended by microsoft for automating office. Now the problem is since we are not running under interactive account I am worried how will it handle the normal popups of office while converting to HTML
 
Please reply me if you have answer for this.
 

GeneralRe: Avoid POP upsmemberkubben10 Aug '06 - 3:55 
Pop ups are a problem. In my experience if you are not allowing the automation to be visible you will have less issues with pop ups. That is if you use this code:
wordApp.Visible = false;
You still can have some trouble, but in most cases you should be able to get around it by calling the methods correctly, so there is no need to prompt. If you need the wordapp to be visible, then I am not sure what you can do about the pop ups.
Sorry I couldn't be more helpful.
 
Ben
GeneralLot of problems with office automationmemberIamADotNetGuy4 Aug '06 - 1:12 
Hi,
 
We are trying to convert word and excel to html format, we are using late binding to support different version of office. We have already taken care of setting dcom security to interactive user and also we have given [B]'launch and active'[/B] and [B]'Access permissions'[/B] for aspnet(Network service in case of 2003) user.
 
The problem is it works absolutely fine in some systems, but it will not work in some systems and throws error as Unauthorizedaccess for CreateObject call.
 
The only difference i could see in working and non working system is, in working system dcom services of excel and word are running with name like "Microsoft Excel Application", but in nonworking system these servies are runnig with GUID like "00020812-0000-0000-C000-000000000046", and this is just a difference i saw I am really not sure whether problem is because of this only or not.
 
PS: We are noy supposed to impersonate aspnet user, so in our web confgi we set impersonation to false.
 
This is kiiling my time i dont have any clue on how to go abt this,
 
System.Type WordType = Type.GetTypeFromProgID("Word.Application");
WordApp = Activator.CreateInstance(WordType,true);

string Version = Convert.ToString(WordApp.GetType().InvokeMember("Version",System.Reflection.BindingFlags.GetProperty,null,WordApp,null));
...
...
...
if (Version.StartsWith("9.") || Version.StartsWith("10."))
{
...
...
WordDocs = WordType.InvokeMember("Documents",System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Public ,null,WordApp,null);
wrdDoc = WordDocs.GetType().InvokeMember("Open",System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public,null,WordDocs,oParamDocPath);
wrdDoc.GetType().InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public,null,wrdDoc,oParamHtmlPath);
WordApp.GetType().InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public,null,WordApp,null);
 
}
GeneralRe: Lot of problems with office automationmemberkubben4 Aug '06 - 3:05 
Hello,
 
So it seems to me that on some level the office automation is running on the client's PC. If this is true, I have seen some weird errors that are caused by not having the .net hooks installed. What this means is that the installation of office probably happened before the .net framework was loaded on the client machine. Or if the .net framework did exist for some reason the .net hooks into office were not installed. If you run the office install for Word or excel, you can choose an update or add extra feature. (I can't remember the exact wording) Anyway, if you check all the things that you can add or turn off in an office install one of them is the .net programming or something like that. My guess is that the computers that don't work don't have this installed.
 
That is my best guess for know. I hope that helps.
 
Ben

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 2 Dec 2005
Article Copyright 2005 by kubben
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid