Posts Tagged ‘macros’

h1

Word: Change case after a period

February 2, 2012

I couldn’t find an easy way to change the case of a lower case letter after a period using Find/Replace (see Matthew’s 25 January 2012 comment on this blog post). My wildcard skills just aren’t sophisticated enough!

However, I did a bit of hunting on the internet and found a couple of macros. I modified them slightly and this one below is the result.

Full kudos for this macro goes to and DonMacnaughto and Lene Fredborg (http://www.microsoft-word-answers.com/microsoft/Word-VBA/29231545/repeatedly-change-first-letter-after-periodblank-to-uppercase.aspx).

Please note: Be sure that this is what you want to do. I suggest you think about it before trying it (and make a backup of your document!), as it will convert ANY letter after a period followed by a space to a capital letter. While that may be fine in most circumstances, you’ll need to watch for things like ‘e.g.’, ‘i.e.’, ‘etc.’, and any abbreviation/acronym that has periods, for example. Make sure that’s what you want.

Sub ChangeCaseAfterPeriod()

With ActiveDocument.Content.Find
   .Text = ". "
   .Forward = True
   .Wrap = wdFindStop
   .Format = False
   .MatchCase = False
   .MatchWholeWord = False
   .MatchWildcards = False
   .MatchSoundsLike = False
   .MatchAllWordForms = False

Do While .Execute = True
With .Parent
'Include the next character
   .End = .End + 1
'Change to uppercase
   .Case = wdUpperCase
'Make sure to move on to next ". "
   .Start = .End
End With
Loop
End With

End Sub

[Links last checked January 2012]

h1

Word: Macro to set the language for most elements

October 14, 2011

I needed to set the language for all elements of a Word 2007 template to English (Australia). I could set the language for the body of the document easily enough via a simple macro, but this didn’t set the language for the headers, footers, text boxes, or the styles (yes, you can set the language for a style!).

So I asked over at the Microsoft Answers forums and the ever-helpful Greg Maxey came up with this macro, which sets the language for all elements of the document, except the styles. As I had fewer than 20 styles in the template, setting the language for those manually wasn’t an arduous task.

Here’s Greg’s macro — change the language from wdEnglishAUS (two places) if you don’t want Australian English (links to the available languages after the macro).

Public Sub SetLangAllRanges()
Dim rngStory As Word.Range
Dim lngJunk As Long
Dim oShp As Shape
lngJunk = ActiveDocument.Sections(1).Headers(1).Range.StoryType
For Each rngStory In ActiveDocument.StoryRanges
  'Iterate through all linked stories
  Do
    On Error Resume Next
    rngStory.LanguageID = wdEnglishAUS
    Select Case rngStory.StoryType
      Case 6, 7, 8, 9, 10, 11
        If rngStory.ShapeRange.Count > 0 Then
          For Each oShp In rngStory.ShapeRange
            If oShp.TextFrame.HasText Then
               oShp.TextFrame.TextRange.LanguageID = wdEnglishAUS
            End If
          Next
        End If
      Case Else
        'Do Nothing
    End Select
    On Error GoTo 0
    'Get next linked story (if any)
    Set rngStory = rngStory.NextStoryRange
  Loop Until rngStory Is Nothing
Next
End Sub

Languages available in Word, with their wd language ID code:

[Links last checked October 2011; if this macro has helped you, consider making a small donation of thanks to Greg at http://gregmaxey.mvps.org/word_tips.htm]

h1

Word: Macro to insert a formatted table and an automated caption

August 10, 2011

NOTE: These instructions only work for Word 2007 and later; they use Building Blocks, which are only available in these versions of Word. If you are using Word 2003 or earlier, I hope to share a much longer macro with you in a few weeks that does something similar but without the formatting.

Scenario

You need to make it easy for your authors to insert many tables in their documents. So you need to add something to the template that allows them to press a couple of keys and get both a preformatted table and an automated caption inserted.

The tables all need to be formatted the same — same header row shading, height alignment and style; same border color and width; same table row height, alignment and style. Once they’ve inserted a table, the author has to be able to modify it (e.g. merge cells) without those modifications affecting anything else.

Your template uses outline heading numbering, so you want a table caption to be inserted at the same time as you insert the table. The caption is to include the chapter number and a sequential caption number (e.g. if they’re in section 2, you want the tables they insert in section 2 to be numbered Table 2-1, Table 2-2 etc.).

Solution

While Quick Tables are an option, you won’t get the caption inserted with them. So this solution takes Quick Tables a couple of steps further.

Step 1: Set up the table

  1. Open your Word template — the template itself, NOT a document based on the template.
  2. Create a table in your template and format it as you want. I suggest you create a table that’s four column by five rows — authors can add/remove rows and columns later.

When creating your table, make sure you:

  • apply the relevant styles to the table header row and the table rows
  • set the row heights for the table header row and the table rows
  • set the alignments for the table header row and the table rows
  • apply shading to the table header row
  • set the table header row to repeat across pages (if required)
  • apply table borders — line styles, color, and widths
  • do whatever else is required to make your table follow your corporate style.

Step 2: Save the table as a Building Block

  1. Select the entire table.
  2. Go to the Insert tab > Quick Parts.
  3. Select Save selection to Quick Part gallery.
  4. In the Create New Building Block dialog box, give the selected table a unique name (e.g. corporate_table).
  5. Change the Save in location from the default Building Blocks.dotx to your template (e.g. corporate_template.dotm). If your template is not listed, then you didn’t create the table in your template — start again at Step 1: Set up the table. Changing the saved location is CRITICAL as you want to share this table with all users of your template; as far as I know, Building Blocks.dotx is a local file on each person’s local machine and it’s not easy to transfer building block entries from one machine to another.
  6. Click OK.
  7. Delete the table from your template, if required.
  8. Save the template but don’t close it.

Step 3: Create a macro that inserts the table and its caption

  1. Go to the Developer tab. (Here’s how to turn it on in Word 2007 and Word 2010.)
  2. Click Macros.
  3. Type Table in the Macro Name field at the top of the Macros window.
  4. Click the drop-down box for Macros in and change the setting to your template (e.g. corporate_template.dotm (template)).
  5. Click Create.
  6. Copy the code in the yellow box below — copy it all; some is not displayed fully, so make sure you drag your cursor over the entire set of code when you copy it.
  7. In between Sub Table() and End Sub, paste the code you just copied.
  8. Make any changes required. You’ll need to change the name of the BuildingBlockEntries from “corporate_table” to the name of your Building Block. Other suggested changes are listed below the macro.
  9. Close the Visual Basic window and save the template (don’t close it yet).
' Insert Table from Building Blocks in template, insert auto caption with chapter numbering
'
'
With CaptionLabels("Table")
        .NumberStyle = wdCaptionNumberStyleArabic
        .IncludeChapterNumber = True
        .ChapterStyleLevel = 1
        .Separator = wdSeparatorHyphen
End With

    Selection.InsertCaption Label:="Table", TitleAutoText:="", Title:="", _
        Position:=wdCaptionPositionAbove, ExcludeLabel:=0
    Selection.TypeText Text:="   <Table Title>"
    Selection.TypeParagraph 

    ActiveDocument.AttachedTemplate.BuildingBlockEntries("corporate_table" _
      ).Insert Where:=Selection.Range, RichText:=True

Other changes you might want to consider:

  • This code has a hyphen (wdSeparatorHyphen) as the separator between the chapter number and the sequential table number — you can change it to something else. These options are available: wdSeparatorColon, wdSeparatorEmDash, wdSeparatorEnDash, and wdSeparatorPeriod.
  • When the caption is inserted, it automatically adds three spaces after the table number and inserts <Table Title>, which is selected ready for the author to change it — if you don’t want the three spaces, or the text, change them within the double quote marks on the Selection.TypeText Text:=”   <Table Title>” line.

Step 4: Assign the macro to a key combination

To make it easier for your template’s users, assign this macro to a key combination so they can just press a couple of keys to get a formatted table with its caption inserted every time.

  1. Open the relevant Customize window:
    • Word 2007: Office button > Word Options > Customize (or click the little drop-down arrow to the far right of the Quick Access Toolbar)
    • Word 2010: File > Options > Customize Ribbon.
  2. At the bottom of the left panel, click the Customize button.
  3. Scroll down the Categories list (on the left) to the end, then select Macros.
  4. In the list of macros on the right, select Table.
  5. Click in the Press new shortcut key field.
  6. Press the keys you want to assign to this macro — e.g. Alt+Shift+T.
  7. Click the drop-down box next to the Save changes in field, then select your template.
  8. Click Assign.
  9. Click Close.
  10. Click OK to close the Customize window.
  11. Save your template, but don’t close it yet.

Step 5: Test!

The final step is to test that the key combination invokes the macro and that the table and its caption is inserted as you expect.

  1. Go to any blank space in the template after Heading 1, then press the key combination you assigned earlier (e.g. Alt+Shift+T) — the formatted table and its automated caption should be inserted correctly.
  2. Be daring — try another one!
  3. Now delete those tables you just added and save and close the template.
  4. Next, open a new document based on the template and test out the key combination there too.
  5. Distribute your template to your authors and let them know how to insert a table the quick way using the key combination you assigned.

[Links last checked August 2011]

h1

Word: Macro to change first letter after a colon to upper case

July 18, 2011

Scenario

You have a Word document where one or more authors have variously used upper and lower case for the first letter of the first word after a colon (e.g. Note: This… and Note: this… ). For consistency and compliance with your style guide, you want to capitalize every initial letter immediately following a colon.

Solution

Run a macro to make the first letter after a colon a capital letter.

The critical parts of this find/replace macro are:

  • .Text = “: ([a-z])” — Word looks for a colon followed by a space, then a wildcard command for any lower case letter
  • .MatchWildcards = True — Word treats the .Text values in the parentheses as a wildcard string
  • Selection.Range.Case = wdUpperCase — When a lower case letter after a colon and a space is found, Word changes it to upper case.

Macro to capitalize the first letter after a colon

Sub CapsAfterColon()
    With Selection.Find
        .ClearFormatting
        .Text = ": ([a-z])"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute
        While .Found
            Selection.Range.Case = wdUpperCase
            Selection.Collapse Direction:=wdCollapseEnd
            .Execute
        Wend
    End With
End Sub

Other options

If always you want the first letter after a colon and space to be in lower case, make these changes to this macro:

  • .Text = “: ([A-Z])” — Word looks for a colon followed by a space, then a wildcard command for any upper case letter
  • Selection.Range.Case = wdLowerCase — When an upper case letter after a colon and a space is found, Word changes it to lower case.

If a macro is too scary for you, you can partially run this as a Find/Replace action. Type : ([a-z]) in the Find field, click More and select Match Wildcards, then click Find Next to find the first instance. You can then change each found word’s initial letter to upper case, one at a time.

[Links last checked June 2011; this macro is a modification of one from Allen Wyatt's Word VBA Guidebook (http://store.tips.net/T010353_Word_VBA_Guidebook_Table_of_Contents.html)]

h1

Word: Macro to show all formatting on opening a document

July 13, 2011

I’ve written before about using a macro to show all formatting marks, bookmarks, table grid lines and field shading before, and just yesterday I gave you a macro for turning off the track formatting option in Track Changes. The problem is that these macros require user input to run.

So what if you find these options pretty clever and want to include them in your template so that every time you opened a document based on that template, they’d automatically run and the author wouldn’t have to remember to run them? For that you need to add them to the AutoOpen() macro.

AutoOpen and AutoNew macros are inbuilt into Word, and anything you include in them is automatically run whenever you open a document (AutoOpen) or create a new document (AutoNew) based on the template.

Here’s how to incorporate the two macros above into an AutoOpen() macro:

Sub AutoOpen()

' macro to display bookmarks, field shading, formatting marks, _
table grid lines and turn off Track Formatting in Track Changes _
on opening an existing document based on the template 

With ActiveWindow.View
   .ShowAll = True
   .ShowBookmarks = True
   .FieldShading = wdFieldShadingAlways
  If ActiveDocument.ActiveWindow.View.TableGridlines = False Then
     ActiveDocument.ActiveWindow.View.TableGridlines = True
  End If
End With

With ActiveDocument
   .TrackFormatting = False
End With

End Sub

[Links last checked July 2011]

h1

Word: Macro to turn off Track Formatting

July 12, 2011

If you use Track Changes a lot — as my authors and their reviewers do — then you may find that formatting changes are often tracked, along with insertions and deletions. I think that the Track Formatting setting travels with the document — I have my setting turned off, but I’ll often get documents that have it turned on and I have to turn it off again, so it doesn’t appear to be computer-specific, just document-specific.

Sure, you can turn off the Track Formatting option in the Track Changes settings (Word 2007 and later), but this won’t accept those changes already tracked — it just prevents the tracking of future formatting changes. You can also accept just the formatting changes. But both these methods require you to take action.

But what if you want to turn off that setting automatically for any document that you create or open? You can, if you add this to any AutoNew() (applies setting to new documents on creation) and/or AutoOpen() (applies setting to existing document on opening) macro in your template, or in a separate macros document that applies to all documents:

With ActiveDocument

    .TrackFormatting = False

End With

So, if you don’t already have an AutoOpen() macro, then the complete macro would look like this (AutoNew() is the same — just copy and paste this macro and replace AutoOpen with AutoNew):

Sub AutoOpen()

   With ActiveDocument

      .TrackFormatting = False

   End With

End Sub

[Links last checked July 2011]

h1

Word: Macro to change headings to sentence case

July 1, 2011

Scenario

You have a long Word document where one or more authors have used various cases for the headings — sentence case (first letter of the first word is capitalized), title case (first letter of all words or all main words are capitalized), and upper case (all words are capitalized). It’s a mess and you need to change all headings to be sentence case.

Solution

Run a macro to change the case based on a heading style.

For example, run the macro once to change the case of all Heading 1s, then change the heading style (Heading 1 below) in the macro code and run it again to change all Heading 2s; repeat for Heading 3s, Heading 4s, etc.

There’s probably a more elegant solution to find and change all heading styles at once, but as this is likely to be something you only use a few times, the extra effort to change the heading style’s name before each run is not arduous.

Macro to change headings to sentence case, based on the heading style

Sub ChangeCase()
    With Selection.Find
         .ClearFormatting
         .Wrap = wdFindContinue
         .Forward = True
         .Format = True
         .MatchWildcards = False
         .Text = ""
         .Style = ActiveDocument.Styles("Heading 1")
         .Execute
         While .Found
             Selection.Range.Case = wdTitleSentence
             Selection.Collapse Direction:=wdCollapseEnd
            .Execute
         Wend
     End With
End Sub

Other options

Sentence case is defined in the macro by wdTitleSentence, but what if you want something different? Substitute wdTitleSentence with one of these options:

  • wdLowerCase — all lower case (probably not what you want as you’ll need an initial capital for a heading)
  • wdTitleWord — every word in the heading has initial capitals (including all the little words like ‘is’, ‘the’, ‘a’, ‘an’, ‘by’, ‘for’, etc.)
  • wdUpperCase — all upper case

There are other options too, but these are the main ones you’re likely to use.

If a macro is too scary for you, you can quickly change one heading at a time by selecting it, then pressing Shift+F3 one or more times in succession to toggle through the various cases.

[Links last checked June 2011; this macro is a modification of one from Allen Wyatt's Word VBA Guidebook (http://store.tips.net/T010353_Word_VBA_Guidebook_Table_of_Contents.html)]

h1

Word: Macros to delete all tables and figures

June 23, 2011

I have NO idea why you might want to do this, but figured I’d share these two macros — one is to delete all tables, and the other is to delete all figures from a Word document.

The macro to delete all tables is from Allen Wyatt’s Word VBA Guidebook (http://store.tips.net/T010353_Word_VBA_Guidebook_Table_of_Contents.html); the one to delete all figures was one I created based on the tables one. However, it wasn’t easy! Unlike tables (Table object), figures aren’t under normal words like ‘figure’, ‘picture’, ‘photo’, ‘diagram’, or ‘image’ — no, they are part of the InlineShape object! That bit of information took some time to find.

Please use with caution — these macros WILL delete every table or figure, except those in your document’s headers and footers.

Macro to delete all tables in a document

Sub TablesDeleteAll()
    Dim tbl As Table
    For Each tbl In ActiveDocument.Tables
        tbl.Delete
    Next tbl
End Sub

Macro to delete all figures in a document

Sub FiguresDeleteAll()
    Dim fig As InlineShape
    For Each fig In ActiveDocument.InlineShapes
        fig.Delete
    Next fig
End Sub

[Links last checked June 2011]

h1

Word: Copying macros from one document to another when the Organizer doesn’t work

January 10, 2011

Scenario

You have a Word template with some useful macros. You’re setting up a new template unlike the previous one, but you want to use some of the useful macros that are contained in the first template. You try to use Word’s Organizer function but you get a message that The project item cannot be copied.

I think this message relates to situations where you try to copy containers for the macros (such as NewMacros and modMain) from one document to the other. But if the containers are the only options listed, you don’t have a lot of choice — and you can’t copy individual macros across using the Organizer.

What to do?

Possible solution 1

My first suggested solution is to put all common macros that you want to apply to all templates, documents etc. into a single macros file that you then include in your STARTUP directory. See http://cybertext.wordpress.com/2009/10/18/word-separate-out-macros-and-attach-them-to-all-documents/ for details.

However, while this solution is fine for documents on your computer where you’re the only author, it’s not such a good solution when you want to distribute the template to others. With multiple authors and multiple computers, you should really keep the macros with the template — you can’t guarantee that other authors will put the macros file into their STARTUP directory, nor replace the file when a new one is created.

Possible solution 2

The second solution is to manually copy and paste the macros from Template A into Template B. This is fairly easy to do but it’s easy to get confused with where you are, so take your time.

Here are step-by-step instructions for doing this in Word 2007 (this looks like a long set of steps, but several steps are repeated for each macro container):

  1. First check if you can copy the macros from Template A to Template B using the Organizer. If you can’t, then continue following these steps. If you can, then skip to Step 18.
  2. Open Template A and Template B. NOTE: Open the templates, not documents based on the templates. Template A is where the macros are located; you’ll be copying them into Template B.
  3. In Template A, go to the Developer tab > Code group and click the Macros button.
  4. Select any of the macros belonging to this template, then click Step Into.
  5. In the top left panel of the Visual Basic window, locate the name of the TemplateProject you have open now (Template A’s name). Template B will also be listed (as may others); only choose Template A’s TemplateProject name.
  6. Expand it, then expand the Microsoft Word Objects and Modules folders of Template A. You should see ThisDocument under Microsoft Word Objects and modMain and NewMacros under Modules.
  7. Double-click ThisDocument in the top left panel to bring its window to the front in the right panel.
  8. If you want all the macros listed in this window, press Ctrl+A then Ctrl+C to copy them to the clipboard; if you only want some of these macros, then copy/paste them one at a time into the text file, making sure you capture the (Private/PublicSub and End Sub lines of each macro.
  9. Go to the TemplateProject name for Template B, and expand its folders.
  10. Double-click ThisDocument in the top left panel to bring its window to the front in the right panel. Remember, you should be working in the TemplateProject for Template B.
  11. Paste the copied text into Template B’s ThisDocument window.If there are existing macros in here you want to keep, go to the end of the window and paste the macros at the end.
  12. Go back to the Template A folders. Double-click modMain in the top left panel to bring its window to the front in the right panel. Copy the macros.
  13. Now go back to the Template B folders. Double-click modMain in the top left panel to bring its window to the front in the right panel. Paste the macros.If there are existing macros in here you want to keep, go to the end of the window and paste the macros at the end. Remember, you should be working in the TemplateProject for Template B.
  14. Go back to the Template A folders. Double-click NewMacros in the top left panel to bring its window to the front in the right panel. Copy the macros.
  15. Return to the Template B folders. Double-click NewMacros in the top left panel to bring its window to the front in the right panel. Paste the macros. If there are existing macros in here you want to keep, go to the end of the window and paste the macros at the end. Remember, you should be working in the TemplateProject for Template B.
  16. Save the changes to the Visual Basic window and close it.
  17. Save the changes to Template B.
  18. You may have lost your macro keyboard shortcuts to the macros –check first, then re-assign them in Template B, if necessary.
  19. Finally, test that the macros and your keyboard shortcuts all work as you expect. Debug as necessary.
  20. Do a final save.

See also:

[Links last checked January 2013]

h1

Word 2007: Insert an odd page break before each Heading 1

December 15, 2010

I’m testing setting up a template for a potentially very large Word document (hundreds of pages) that will be printed and bound. I want each section/chapter to start on a new, odd page, so I want to associate an odd page section break with my Heading 1 style.

Problem: You can’t do this in Word! You can easily insert a page break before a style, but not a section break. Go figure…

However, you can create a macro that will insert an odd page section break in front of your Heading 1 style. Please note: If you use the Heading 1 style for anything other than your new chapter/section heading, the odd page section break will apply to that too.

The macro below is modified from the one I found here: http://thedailyreviewer.com/windowsapps/view/inserting-a-section-break-before-each-heading-level-1-automatically-10694987

This macro inserts an odd page section break before a Heading 1 style.

Sub  InsertOddPageSectionBreak()
Dim rngDcm As  Range
Dim rngTmp As  Range
Set rngDcm =  ActiveDocument.Range
With  rngDcm.Find
.Style = "Heading  1"
While  .Execute
rngDcm.Select ' for  testing only
Set rngTmp =  rngDcm.Duplicate
rngTmp.Collapse
rngTmp.Select ' for  testing too
If  Asc(rngTmp.Characters.First.Previous) <> 12 And _
Asc(rngTmp.Characters.First)  <> 12 Then
rngTmp.InsertBreak  Type:=wdSectionBreakOddPage
End  If
rngDcm.Collapse  Direction:=wdCollapseEnd
Wend
End  With
End Sub

You can modify it to apply to any named style (replace Heading 1 in the quote marks with any other named style, and you can modify the type of break that’s inserted (e.g. change wdSectionBreakOddPage to wdSectionBreakNextPage).

Thanks to Helmet Weber (Microsoft Word MVP) whose macro pointed me in the right direction.

[Link last checked December 2010]

Follow

Get every new post delivered to your Inbox.

Join 232 other followers