You are on page 1of 28

Getting Started Using VBA: The Word Working Partner

Microsoft Word is an amazingly complete and complex environment to work in. Most of us wordsmiths (and I count myself as one since I write a lot) don't use even a part of the capability that is built into Word. So it's natural to ask the question, "Why do I need even more capability in VBA programs that I write myself?" Read On and See! (This tutorial is based on Word 2007.) No matter how many features Microsoft builds into Word, there are going to be things that you will want to do over and over in lots of documents. There may also be functions in other documents, like part of an Excel spreadsheet, that you want to use in your Word document. And ... Microsoft may have simply left out a feature that you want to have available in your "personalized" version of Word. To introduce you to Microsoft Word VBA programming, we're first going to code a very short program that is sort of a "bootstrap" for learning to program VBA. After that's done, we'll create a few more short VBA programs to illustrate components, and provide additional code samples. We're going to create a program that starts automatically and displays the path to the Word "startup folder". In order to do this, we're going to have to find out what the startup folder is. Before you say, "Hey! You can just go to Office Button > Word Options > Advanced > File Locations tab and see what the startup folder is. It's probably C:\Users\myComputer\AppData\Roaming\Microsoft\Word\STARTUP anyway." We're doing it this way to learn how to code Word VBA programs. First, start Word 2007. Look for the "Developer" tab. It's not turned on by default so if it's not visible, click the Microsoft Office Button, and then click Word Options. Click Popular, and select the Show Developer tab in the Ribbon check box. That should add a new "Developer" tab to your system. Click that tab to bring up the Visual Basic development environment and then click the Visual Basic icon to launch the VB editor.

-------Click Here to display the illustration Click the Back button on your browser to return --------

Click the Module option under the Insert menu. Enter this code. (Note that long lines are broken into shorter lines using the "_" continuation character in most examples here. You can enter these lines without the continuation if you want to.) Public Sub AutoExec() MsgBox ("The Word 2007 Startup Folder is: " _ & vbCrLf & Word.Application.StartupPath) End Sub Press F5 to display the list of macros in your document and select AutoExec. Then click Run. You should see a MessageBox display something like this. Click the OK button on the MessageBox and then close the Visual Basic Editor. Save the document as a "Word macro enabled template" document type in the folder that you have now learned (from the message in the MessageBox) is the startup folder. It doesn't matter what you name the document template as long as it is in the startup folder. Now, close Word and restart it. This time, you should see the MessageBox displayed as soon as Word opens.

You probably don't want this message to be displayed whenever you open Word from this point on. To stop it, just delete the document template you saved earlier from your startup folder.

-------Click Here to display the illustration Click the Back button on your browser to return --------

But you want to do more than just figure out what the Word startup folder is. On the next page, we write a really simple, but still useful program. (Continued from Page 1) There are lots of applications that you might want to run when Word starts that are possible now that you know how to do it. For example, if you use Word mainly to write letters and only occasionally for something else, you could write an AutoExec program to ask whether to load a default "personal letter" or the generic Word environment. (A followup article, Word and Excel Working Together, shows you how to automate the process of writing a "form letter" using VBA macros.)

Public Sub AutoExec() Dim MsgBoxResult Dim SaveFileName MsgBoxResult = _ MsgBox("Click Yes to load the default letter" _ & vbCrLf & "Click No to load default Word.", _ vbYesNo, "Document Environment") If MsgBoxResult = vbYes Then Documents.Open _ ("C:\Users\myComputer\Documents\DefaultLetter.doc") SaveFileName = _ InputBox("Enter a name for the letter", _ "Letter Name ?") If SaveFileName <> "" _ Then ActiveDocument.SaveAs (SaveFileName) End If End Sub -------Click Here to display the illustration Click the Back button on your browser to return --------

There's a lot to be improved in this program. For one thing, the document is saved in your main Documents folder. You might want to add code to allow it to be saved somewhere else. Adding your unique personalizations is left as an excercise for the reader. AutoExec in the startup folder is a holdover from the old WordBasic (a "true" macro language rather than the more Object Oriented VBA). VBA still supports a number of the old WordBasic commands and this is one of them. It works because a "magic procedure" Autoexec - is in a particular place with a particular name. Using an event subroutine that is triggered by a "method" of the Application or Document object is a more Object Oriented way to do things like this. Let's see how that's done next. What is a software object? In brief, it's a program that has properties, like "Name" for example, and methods, like "Click" for a Button object, that can be reused in other programs. This leaves a lot out of the definition and "OOP purists" might say it's way too brief. But it's a place to start.

While your Word application has many objects with events that you can use (like the Document object and the Open event will trigger the Document_Open procedure), you can also add your own from the VBA Toolbox. To demonstrate a few simple objects and how to use them in code, let's write a VBA program to automate Word's own capabilities. If you have written Visual Basic programs, but no Word VBA programs, you'll notice a lot of methods and properties you haven't seen before. Every Office application has a different set and it's very difficult to remember them all. At the same time, they're the key to the VBA treasure house. To bridge this problem, you need help! One of the best ways to get help is by using Record Macro. This is a good place to suggest another tip that applies mainly to Word. When using Record Macro, avoid cluttering up the Normal template with your experimental code (or with your completed code unless you really do want to add your program more or less permanently to Word). Save your code in your own document. Or create a another template and save it there. This is something you have to remember to do since the Normal template is the default in Record Macro (even though it probably shouldn't be). -------Click Here to display the illustration Click the Back button on your browser to return --------

But at some point, you have to get in and start writing your own programming code. On the next page, we do exactly that! Continued from Page 2) For the Word program, lets use an "Automated Rating Description System" that substitutes a description for a numeric rating for this course in Word. To create this system, add the text to the document as shown below. -------Click Here to display the illustration Click the Back button on your browser to return --------

Look for a "Developer" tab in Word 2007. It's not turned on by default so if it's not visible, click the Microsoft Office Button, and then click Word Options. Click Popular, and select the Show Developer tab in the Ribbon check box. That should add a new "Developer" tab to your system. Click that tab to bring up the Visual Basic editor and enter the code for the VBA macro. In the editor, Click the Design icon near the top to toggle into design mode. This "turns on" several features in Word and "turns off" others. For example, if you click a Button in design mode, the Button is selected. Out of design mode, clicking a Button will execute the Button Click event subroutine. Click the down arrow beside the Legacy Tools icon to display the controls toolbox. Click the Button control to add it to your document. Remember that controls are added "in line" with your text so position the insertion point where you want the Button to be before adding it. Click Properties to change the Name and Caption properties of the Button.

-------Click Here to display the illustration Click the Back button on your browser to return --------

You can add the event subroutine that is called when the Button is clicked automatically by double clicking the Button. This opens the Visual Basic code editor window and fills in an initial shell of the subroutine all at once. The completed code in the shell is shown below. Private Sub RateCourse_Click() If ActiveDocument.Bookmarks.Exists("Rating") = True Then ActiveDocument.Bookmarks("Rating").Select theRating = Selection.Text Selection.MoveRight _ Unit:=wdCharacter, Count:=1, Extend:=wdExtend Selection.TypeText "" Else MsgBox ("Rating system bookmark missing!") End If Select Case theRating Case "1" Selection.Text = _ "Huzza! Great! Loving It!" Case "2" Selection.Text = _ "Not the most wonderful but still quite good." Case "3" Selection.Text = _ "It's OK I guess. Seen better and seen worse." Case "4" Selection.Text = _ "It's a start but it needs work." Case "5" Selection.Text = _ "What a pile of GARBAGE!" Case Else

Selection.Text = _ "Must be a number from 1 to 5. Try again." End Select End Sub It's a pretty simple system. The user enters a number and clicks a Button. Then the Word VBA macro above replaces the number with a phrase. And it could use some improvement. For example, the program depends on the existance of a Bookmark named "Rating" in the document. This can make the program fail to work after a fairly simple change - deleting the part of the document containing the Bookmark. (This technique works best if the document is a read-only "Template" so the user doesn't change anything accidentally.) The number that was entered is then Selected ... Selection.MoveRight _ Unit:=wdCharacter, Count:=1, Extend:=wdExtend ... and then overwritten ... Selection.TypeText "" ... just to make the result look a little nicer. Again, this simple macro isn't very foolproof and in production systems, you're going to want to spend a lot more time thinking about what your users are actually going to do when then run the system. Finally, the rating text is inserted into the document using a Select Case statement: Select Case theRating Case "1" Selection.Text = _ "Huzza! Great! Loving It!" etc. ... As simple as it is, this system does illustrate a lot of important techniques that you can use to build a much more complicated system. If you're interested in trying a little more complicated system using both Word 2007 and Excel 2007 together, try this article!

Word and Excel Working Together Adding power with custom programming to host applications like Word or Excel is a primary benefit of VBA, but the next level up is using VBA with Word and Excel together. The techniques demonstrated here will only use these two host applications, but keep in mind that you can use any combination of Office apps that you need. Do you need to insert custom numbers into a Visio flowchart from Excel along with text from Word? Not a problem! If you would like to start at a more basic level with just one, however, try this article written for people just starting out: Getting Started Using VBA: The Word Working Partner. (This article is based on Word and Excel 2007.) Let's see how this works ... In this segment, we're going to use features from both Word and Excel to create two custom letters. The first letter just copies phrases from an Excel worksheet. The second letter lets you select any group of cells and copies those to a predefined location using the clipboard. The first thing we'll have to do is to decide which application will serve as the "host environment". Visual Basic .NET, the full system and not the version used inside Word and Excel, can be thought of as simply another hosting environment for Word and Excel. In other words, you can use the features of Word, Excel, or other Office applications inside a VB.NET program in a way that is very much like the way you use them in VBA. Whenever you need to use features from several Office apps in the same program, VB.NET should be a top choice as a development environment. This site has a number of articles that use VB.NET along with Office systems. In COM - .NET Interoperability in Visual Basic, I show how to use an Office application inside a VB.NET program. On the other hand, VB.NET might not be available to you. Or your application might fit "naturally" into one of the other host applications. In this article, we're going to use Word as our host and then incorporate features from Excel. The sample application developed here consists of two "customizable letters". The first letter lets someone choose just the right phrase from lists of pre-composed phrases in Word. These are inserted into the document at locations premarked with Word "bookmarks". The Excel spreadsheet includes the most current values of key numbers that are also inserted into the first letter.

But suppose you want to insert part of spreadsheet that varies in size or location? The second letter lets someone select a part of a worksheet with a mouse and then copies it into a location in the letter using the Clipboard. To start out, I composed a document in Word with "boilerplate" text that doesn't change and added Bookmarks where pre-composed phrases and the spreadsheet contents will be inserted. If you're following along at home, you might want to change your Word display options to be able to actually see the Booknmarks. Go to Office Button > Word Options > Advanced and look under the Show Document Content header for the Show Bookmarks checkbox. -------Click Here to display the illustration Click the Back button on your browser to return --------

On the next page, we add Excel 2007 into the programming mix and then bake well. (Continued from Page 1)

For the Excel part of the system, I created an Excel workbook to provide numbers for the Word document. Names were assigned to the cells containing the numbers using the Excel Name Manager in the Formulas tab. The workbook is pretty simple since the goal is only to demonstrate Word and Excel working together. For the first letter, the a worksheet provides two numbers: a calculation of days using the current date and a date in the past, and a simple amount. Date calculation is a good example of something that Excel can do very well but Word has less capability. -------Click Here to display the illustration Click the Back button on your browser to return --------

The second letter uses a block of values from a different worksheet that will be copied and pasted under program control. This is covered on pages 4. Designing the System The next thing to decide is how the user will interact with Word and Excel in our system. In this system, the Excel workbook is updated independently. That means that the

numbers from the Excel workbook are simply extracted and inserted into the Word document using VBA programming. Another "user interface" issue is where to place the VBA code and how to present controls to the user. In both of our letters, we add a UserForm to the system and place controls on that. It's quite possible to place the controls (Buttons, Listboxes) directly into the Word document rather than adding a Windows form and placing them on the form. Placing controls directly into a document can work very well for some applications but it just creates difficulties in our system (although there is one control that is placed directly on the second worksheet. In general, you gain a lot of flexibility by using a UserForm to contain your controls. I'll cover this again when we look at the actual VBA code. -------Click Here to display the illustration Click the Back button on your browser to return --------

The Word Document VBA Code In this system, a UserForm is displayed along with the Word document when the document is opened. This Form will hold six Button controls, four ListBox controls, and a Label that

displays a title. This design decision tells me where at least some of the VBA code will have to be: in the Open event for the Word document to display the Form. When the Document is opened, the Document_Open subroutine is executed and the Form is displayed. The rest of the VBA code is in the UserForm. Here's the display in the VBA editor of the finished system showing where the program code can actually be found. Keep in mind that in VBA, these aren't files. They're all incorporated right into the Word or other Office document itself so you won't see them anywhere on your computer. To open the Form, VBA code in the Open event of the Document is used. The Open event does two things:

Phrases are loaded into listboxes for later use The Form (frmDocPhrases) is displayed Here's what the Open event code looks like:

Private Sub Document_Open() ' Salutation Names Call initSal ' Agent Names frmDocPhrases.lstAgent.AddItem "attorney" frmDocPhrases.lstAgent.AddItem "attack dog" frmDocPhrases.lstAgent.AddItem "maiden aunt" frmDocPhrases.lstAgent.AddItem "bookie" frmDocPhrases.lstAgent.AddItem "worst enemy" ' Agent Acts frmDocPhrases.lstAgentAction.AddItem "file suit" frmDocPhrases.lstAgentAction.AddItem "run and hide" ... (see the downloadable system for the rest)

This example is not a model of excellent system or interface design. It's as simple and uncomplicated as possible while still getting across the main points. For example, a real system would probably load the listboxes from a file or database and would likely have a satellite system that made it easy to update and change the phrases. Another problem is that this design requires a change to the VBA code to change any phrase - not a good design choice! This program also doesn't have any error handling and a real one most certainly should include it. The rest of the system consists of the design and code for a separate UserForm. On the next page, you learn how to add it. (Continued from Page 2) The next thing to do is to design and build the form frmDocPhrases and start writing code for it. Here's what the form looks like:


-------Click Here to display the illustration Click the Back button on your browser to return --------

(I also added a button at the bottom of this form to kick off the second letter. That's not shown in the illustration because this article was updated and it's not necessary for the first letter.) There are six bookmarks in the document and each one is updated by a command button. The top four display a listbox selection and the bottom two get information from the Excel workbook. Earlier, I mentioned that it's probably not a good design choice to place controls into the Word document. The problem is that when you place controls into the document, they're actually Word fields that act a lot like the rest of the text in Word. They have all the limitations

(and some advantages) that fields have. For example, you can delete them while you're editing the document. Here's a concrete example of how a separate form can be better than a component that is coded as a field in the Word document. In this program, all of the Listboxes are in exactly the same space on the form frmDocPhrases. The program reuses that exact same space by making only one Listbox visible at a time. The type of Listbox that can be placed in the Word document doesn't even have a Visible property and there is no way to place them in the same space in the document. When a Button is clicked, the Click event subroutine is automatically executed. Here's the code for the first one (cmdSal) as an example:

Public Sub cmdSal_Click() ' Make sure the other list boxes are hidden HideListBoxes ' Find the right bookmark Selection.GoTo What:=wdGoToBookmark, Name:="SalName" lstSal.Visible = True lblListBoxTitle.Caption = "Select a salutation" End Sub

This code above is for the Salutation command button. The other three are very similar, but this one has a key difference. To be able to call the first command button subroutine from the document VBA code, we have to make a change in the way the initial subroutine code is automatically entered for us by the Visual Basic editor. The editor automatically creates an empty default subroutine like this:

Private Sub cmdSal_Click() End Sub

You have to change the Private keyword to Public. The code in the Document_Open() subroutine in the Word document has to be able to locate the subroutine in the frmDocPhrases form. Because they're in different modules, the Private keyword would prevent it. This is true even though they're stored in the same file (the Word document). The rest can remain Private because now they're being called from the same module. This is a good example of the concept of "scope" in Visual Basic programming. When an item in the Listbox is clicked, the text in the item is inserted into the Word document using this code:


Private Sub lstSal_Click() Selection.TypeText (lstSal.Text) End Sub

And the final "Word only" subroutine is simply an internal utility Sub to avoid repeating identical lines of code in several places. This hides all of the Listbox components and then the one that is need is made visible again.

Private Sub HideListBoxes() lblListBoxTitle.Caption = "" lstSal.Visible = False lstAgent.Visible = False lstAgentAction.Visible = False lstCondition.Visible = False End Sub

VBA Code Calling the Excel Server In a way, all of this has been preparation for the actual subject of this article: using Excel functions inside a Word VBA program. The subroutines that handle the Click event for the bottom two command buttons are where this takes place. First here's the code, then I'll explain what it means:

Private Sub cmdUpdtAmt_Click() HideListBoxes Set myWB = _ GetObject("{your path}\ExcelCalculation.xlsm") Selection.GoTo What:=wdGoToBookmark, Name:="AmtDue" Selection.TypeText (myWB.Sheets("PayHist").Range("Amount_Due")) Set myWB = Nothing End Sub Private Sub cmdUpdtTime_Click() HideListBoxes Set myWB = _ GetObject("{your path}\ExcelCalculation.xlsm") Selection.GoTo What:=wdGoToBookmark, Name:="DaysOverdue" Selection.TypeText (myWB.Sheets("PayHist").Range("Payment_Overdue")) Set myWB = Nothing End Sub

At the top of the code module, the VBA code declares an Excel workbook object, myWB. It's declared outside any of the Subs to give it "module scope" so it can be used in both of the Subs that need it. If you just entered this in your code without doing anything else, it would generate an error because Word doesn't recognize Excel.Workbook as a legitimate object. To use objects from other systems, you have to add what is called a "reference" to them. You do this using the Tools > References menu option in the Visual Basic editor. The illustration below shows the Excel objects that were added for this program:

-------Click Here to display the illustration Click the Back button on your browser to return --------

The Excel workbook object must also be "instantiated" using the Set statement. Be sure to replace {your path} in the code above with the actual path on your computer. The next statement positions the Word cursor at the correct bookmark and then the TypeText method in Word uses content from the cell named Payment_Overdue in the PayHist worksheet. Since a copy of the Excel workbook has been made available to the Word program in the myWB object, we get rid of the object again with the final Set myWB = Nothing statement so it doesn't continue to use resources in your computer. Although there is some code duplication here, the Set statement can't be coded outside of a Sub. The First Letter Result Here's one variation showing what the final result could be after running the macro.

-------Click Here to display the illustration Click the Back button on your browser to return --------

On the next page, we code the second letter and use the Clipboard to transfer data instead. (Continued from Page 3) One of the biggest limitations of the previous letter is that specific cells in the Excel spreadsheet have to be named and copied to the form letter. What if the content in the spreadsheet could be any size and in any location? The second letter attacks that problem. The first thing that is done to work on the second letter is performed by a button that was added to the previous UserForm that simply dismisses that one and opens another one:

Private Sub btnClosePhrases_Click() frmDocPhrases.Hide frmGetExcelData.Show End Sub

One way to solve the problem of selecting a random area from the spreadsheet would be to identify exactly what cells have been selected and then place them in some sort of

"container" to be picked up by the code in the Word VBA. Another way would be to pass back the location of the cells. Unfortunately, according to Microsoft, there is no "Active Range" property. But Excel does support the Clipboard! This reduces our effort to just two lines of code inside a subroutine:

Private Sub btnReturn_Click() Selection.Copy SendKeys "%{F4}", True End Sub

Ordinarily, the statement Application.Quit would be used to close Excel and return to Word. But this doesn't work in this case. Actually, Application.Quit doesn't work for a lot of people and the Web is full of complaints about how to get around the problem. Sending the keystroke shortcut that simply closes down any application (Alt-Function4) does the trick, however. The True parameter of SendKeys allows the Alt-F4 to complete before returning control to the macro and can potentially avoid timing problems. The button that is used to trigger the event code shown above is placed directly onto the worksheet. This is an example of what is called an ActiveX control and it's a legacy component of VBA that is still completely supported. The illustration below shows the ActiveX controls in the Excel Toolbox. -------Click Here to display the illustration Click the Back button on your browser to return --------


When the Word document (and the UserForm with buttons) is redisplayed, the content of the clipboard is simply pasted at a bookmark in a way very similar to the first letter and the Excel application is closed. At this point, the Word document can be further customized. (But it should never be saved since the original document is the "template" and shouldn't be changed. Doing something about this problem with a "real" Word template is another way the application could be improved.)

Private Sub btnPasteExcelData_Click() Selection.GoTo What:=wdGoToBookmark, Name:="ExcelContent" Selection.Paste myExcelApp.Quit Set myExcelApp = Nothing Me.Hide End Sub

Two other very minor notes. The Caption property doesn't provide a way for embedding line breaks, so the Caption is initialized in the Workbook_Open event where vbNewline characters can be embedded using code. Also, if you're interested in random number programming, I also decided to simply pick a "Salutation" field for the second letter at random. Download the application and give it a try! Click Here to download. Remember to change the {path} to match your own directory structure, and remember that this is just a "starter" application. Use the ideas here to build a real one of your own!


Sub XL2Word() Dim mswordApp As Word.Application Dim msword As Word.Document Dim msexcelws As Worksheet Let Application.ScreenUpdating = False Let Application.StatusBar = "Criando um novo documento..." Set mswordApp = New Word.Application Set msword = wdApp.Documents.Add For Each ws In ActiveWorkbook.Worksheets Let Application.StatusBar = "Copiando os dados da WorkSheet " & ws.Name & "..." msexcelws.UsedRange.Copy mswordApp.Paragraphs (msword.Paragraphs.Count).Range.InsertParagraphAfter mswordApp.Paragraphs (msword.Paragraphs.Count).Range.Paste Let Application.CutCopyMode = False mswordApp.Paragraphs (msword.Paragraphs.Count).Range.InsertParagraphAfter ' Inserindo uma quebra de pagina aps as worksheets exceto a ultima If Not msexcelws.Name = Worksheets (Worksheets.Count).Name Then With mswordApp.Paragraphs (mswordApp.Paragraphs.Count).Range .InsertParagraphBefore .Collapse Direction:=wdCollapseEnd .InsertBreak Type:=wdPageBreak End With End If Next ws Set msexcelws = Nothing ' Aplica o modo de visualizacao normal With wdApp.ActiveWindow If .View.SplitSpecial = wdPaneNone Then Let .ActivePane.View.Type = wdNormalView Else Let .View.Type = wdNormalView End If End With Set Let Set Let End Sub msword = Nothing wdApp.Visible = True mswordApp = Nothing Application.StatusBar = False


Bernardes. Pelo que vi aqui, acho que ter a resposta para o meu problema. Tenhum uma planilha no Excel 2003, que quero copiar um Range e colar no Word, e depois salvar o doc com um nome que irei especificar. Manualmente seria <ctrl>C no Excel, <ctrl>V no Word e depois salvar como e fechar o Word. Hj consegui abrir o Word, carregar um .doc modelo, fechar o doc e o Word. Est faltando o mais importante que colar a planilha no Word e salvar com o nome que especifico. Poderia me ajudar? Antecipadamente grato. Paulo.

Bom dia, Veja se este exemplo te ajuda: necessrio colocar "Microsoft Word Object Library" nas referncias do VBA Excel.
Sub CopiaExcel_Word() Dim MSWord As Word.Application Set MSWord = New Word.Application [A1:B10].Copy With MSWord .Documents.Add .Selection.PasteExcelTable False, False, False .ActiveDocument.SaveAs "C:\Teste.doc" .ActiveDocument.Close .Quit End With Set MSWord = Nothing End Sub

Obrigado amigo. Funcionou perfeitamente, mas durante a madrugada acabei conseguindo resolver, e apesar de no ter ficado muito diferente do seu, vou mostra meu cdigo. Abraos e mais uma vez obrigado pela sua ateno. Paulo

Sub Copia_Word() Dim appWord

As Word.Application


Dim doc As Word.Document Set appWord = CreateObject("Word.Application") Range("A1:T" & iT).Select Selection.Copy ' Set doc = appWord.Documents.Open(Filename:=planilhaD) ' doc.Range.Paste Application.CutCopyMode = False doc.SaveAs (destinoD) doc.Close appWord.Quit Set appWord = Nothing End Sub


Sub ShowProgress(ByVal snglFileCounter, ByVal snglCount, ByVal strFolderPath As String) Dim snglDecimal As Single Dim snglWidth As Single Dim strLabelText As String If BoolCancel Then Exit Sub Let snglDecimal = snglFileCounter / snglCount Let snglWidth = snglDecimal * 280 Let strLabelText = TruncPathForLabel(strFolderPath) Let frmProgress.lblPercent.Caption = "Folder scan is " & FormatPercent(snglDecimal) & " complete." Let frmProgress.lblStatus.Caption = snglCount & " files in " & strLabelText Let frmProgress.lblProgress.Width = snglWidth frmProgress.Repaint End Sub Sub MakeTable() Dim MyTableRange Dim Active If BoolCancel Then Exit Sub Set Active = ActiveDocument If ActiveDocument.Tables.Count = 0 Then Set MyTableRange = Active.Tables.Add(Range:=Active.Range(Start:=0,End:=0), NumRows:=1, NumColumns:=3) AddMacroButton 1, "MACROBUTTON TableSortAToZ Description " AddMacroButton 2, "MACROBUTTON TableSortAToZ File Path/Name " AddMacroButton 3, "MACROBUTTON TableSortAToZ File Type " With ActiveDocument.Tables(1).Columns(1).SetWidth ColumnWidth:=InchesToPoints(2.3), RulerStyle:=wdAdjustProportional.Columns(2).SetWidth ColumnWidth:=InchesToPoints(4.5), RulerStyle:=wdAdjustProportional.Columns(3).SetWidth ColumnWidth:=InchesToPoints(0.7), RulerStyle:=wdAdjustProportional End With Let lngTableRows = 1 End If Let BoolTableMade = True End Sub Sub AddMacroButton(ByVal lngCellNumber As Long, ByVal strMacroButton As String) Dim CellRange As Range If BoolCancel Then Exit Sub Set CellRange = ActiveDocument.Tables(1).Rows(1).Cells(lngCellNumber).Range CellRange.Select CellRange.Delete Selection.Fields.Add Range:=CellRange,


Type:=wdFieldEmpty,text:=strMacroButton, preserveformatting:=False End Sub Sub pMacroClickOptions() If BoolCancel Then Exit Sub If frmOptions.chkSort.Value = True Then With Options Let .ButtonFieldClicks = 1 End With Else With Options Let .ButtonFieldClicks = 2 End With End If End Sub Function TruncPathForLabel(strText)Dim intLen As Integer Dim intMarkLeft As Integer Dim intMarkRight As Integer Dim strLeft As String Dim strConj As String Dim strRight As String Dim strLabelText As String If BoolCancel Then Exit Function Let intLen = Len(strText) If intLen > 60 Then Let intMarkLeft = InStr(15, strText, "\") Let intMarkRight = InStrRev(strText, "\", -1) Let strLeft = Left(strText, intMarkLeft) Let strConj = "..." Let strRight = "\" & Right(strText, intLen - intMarkRight) Let strLabelText = strLeft & strConj & strRight Let TruncPathForLabel = strLabelText Else Let TruncPathForLabel = strText End If End Sub Sub sOpenBrowser(FileName) Dim Dummy As String Dim RetVal As Long Dim hwnd Let RetVal = ShellExecute(hwnd, "open", FileName, "", Dummy,SW_SHOWNORMAL) End Sub

Formatting Word Text with VBA

When formatting Word text with VBA you can change all the properties in the Format Font dialog box.
' to change the font properties of selected text... With Selection.Font


' the Latin text font name and size... .Name = "Verdana" .Size = 12 ' Bold and Italic are the Font Style... .Bold = False .Italic = False .Underline = wdUnderlineNone .UnderlineColor = wdColorAutomatic ' The following are the font effects... .StrikeThrough = False .DoubleStrikeThrough = False .Outline = False .Emboss = False .Shadow = False .Hidden = False .SmallCaps = True .AllCaps = False .Color = wdColorAutomatic .Engrave = False .Superscript = False .Subscript = False ' Character spacing... .Spacing = -1 .Scaling = 100 .Position = -2 .Kerning = 12 ' One of the available Annimation effects. ' Can be one of the following... ' wdAnimationBlinkingBackground ' wdAnimationLasVegasLights ' wdAnimationMarchingBlackAnts ' wdAnimationMarchingRedAnts ' wdAnimationShimmer ' wdAnimationSparkleText ' wdAnimationSparkleText .Animation = wdAnimationNone The font, size, and style of Bidirectional fonts. .SizeBi = 12 .NameBi = "Tahoma" .BoldBi = False .ItalicBi = False End With

Build an Automatic Document Template for Word


An Introduction to Microsoft Word UserForms Part 1: Preparing the Document Introduction

Save the Document as a Template

When you are satisfied with your document you must save it as a Word Template. When you subsequently use a template you use Word's File > New command to open a copy of the template file rather than the file itself. This means that the original template document remains unchanged and will always open looking the way you intended. Open the File menu and choose Save As to open the Save As dialog. In the Save as type section choose Document Template then enter a suitable name for your template and click Save. NOTE: When choosing a location for your template you should bear in mind that when the user chooses File > New there are taken to the default Templates folder. This is a good place to save templates, as they are easily accessible from here. You can store your templates in any location but you should remember that they should always be opened for use using the File > New command. Only use the File > Open command if you want to open the template file itself for editing. You can also open a template for use by locating its file with Windows Explorer and double-clicking the file's icon. Remember to test your template thoroughly and correct any errors before unleashing it on any other users.