Posts Tagged ‘macros’

h1

PowerPoint: Macro to change the proofing language

January 13, 2024

Caroline Orr, a UK editor, used ChaptGPT to create a macro to set the proofing language in PowerPoint to UK English, which she says works really well—see her second attempt here: https://www.orreditorial.com/chatgpt-powerpoint-macro/

In that second example, ChatGPT used msoLanguageIDEnglishUK in 2 places in the code to set the language to UK English.

If you wanted to use this macro and change it to another language, then refer to this list from Microsoft for the codes for other languages:  https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.core.msolanguageid?view=office-pia

For quick reference, the codes for other commonly used English languages are:

  • msoLanguageIDEnglishAUS
  • msoLanguageIDEnglishCanadian
  • msoLanguageIDEnglishNewZealand
  • msoLanguageIDEnglishSouthAfrica
  • msoLanguageIDEnglishUS

[Links last checked January 2024]

 

 

h1

Word: Macro to change date format from dd MMM YYYY to MMM dd, YYYY

September 11, 2023

In one of the editors’ Facebook groups, VK asked for a macro to change UK date formats (e.g. 12 December 2022) to the US format (December 12, 2022).

The closest I found was this one from the WordMVP site: https://wordmvp.com/FAQs/MacrosVBA/SRChangeDateFormat.htm, but it does the opposite (i.e. changes US to UK format). I thought just moving around some things in the find and replace lines would work, but they didn’t, so after a bit of fiddling, I did get it to work. I’ve copied the complete macro from the WordMVP site in case that ever disappears, but all credit must go to Bill Coan, the author of that macro. The only changes I made were to comment out the two lines for find and replace and replace them with my own.

If you want to use this macro, copy/paste the whole thing as some of the lines may go ‘off the page’ and only copying it all will preserve them.

Update: To avoid it asking about continuing the search if nothing is found for a particular month, you can comment out the .Wrap = wdFindAsk line. You can also comment out the .Format and all the .Match lines, EXCEPT the .MatchWildcard line – you must keep that one.

Sub ChangeDateFormatWithReplaceCommand()

Dim myMonth(1 To 12) As String

myMonth(1) = "January"
myMonth(2) = "February"
myMonth(3) = "March"
myMonth(4) = "April"
myMonth(5) = "May"
myMonth(6) = "June"
myMonth(7) = "July"
myMonth(8) = "August"
myMonth(9) = "September"
myMonth(10) = "October"
myMonth(11) = "November"
myMonth(12) = "December"

For i = 1 To 12
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        ' .Text = "(" & myMonth(i) & ")" & " ([0-9]{1,2}),"
        ' .Replacement.Text = "\2 \1"
        .Text = "([0-9]{1,2})" & " " & "(" & myMonth(i) & ")"
        .Replacement.Text = "\2 \1,"
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
Next i

End Sub

 

[Link last checked September 2023]

 

h1

Word: Macro to find and highlight nominalisations

September 1, 2023

This is variation of my blog post on finding and highlighting a set of vague words.

In the technical reports I edit, the authors regularly create nouns from verbs (aka nominalisation / nominalization), such as the assessment of, the management of, the description of, the maintenance of, the provision of etc. A tell-tale sign is the ‘the’ in front of the phrase and ‘of’ at the end of it. In many cases (though not all), these nominalisations can be replaced with the relevant verb (e.g. assess / assessing, manage / managing, describe / describing, maintain / maintaining, provide / providing).

I wanted to identify and highlight the main nominalisations (typically they end in -tion, -sion, -ment, -ent, -ant, -ity, -ancy, -ency and are usually followed by ‘of’) using a Microsoft Word macro. And then I wanted to add the main ones I come across in my work to my PerfectIt style sheet I use for these clients (I added these under Phrases to Avoid / Consider. with a comment saying ‘Potential nominalisation’). PerfectIt can identify prefixes, but doesn’t have a separate section for identifying suffixes such as these.

I adapted a macro I’d already used to identify and highlight vague words, which is one I adapted from Macropod (Paul Edstein). Full thanks to Macropod for this one. Below the macro is a list of the terms I found in just two client documents—I will add these to PerfectIt for it to check for them in future (Note: Not all the terms listed are nominalisations, but most are; the others use ‘of’ or similar and can likely be written more succinctly. Also note that this macro will result in some ‘false positives’ such as ‘Department of xxx’, which you can ignore).

NOTE:

  • Copy all the code below to the clipboard—some may go off the page, so don’t type it out as you’ll miss some of it or could make a typo—then paste it into your VBA window.
  • If you wish to add your own suffixes to the list, make sure you start immediately after the comma separator in the StrFind line then add a space after ‘of’ before the next comma separator.
Sub Nominalisations()

' Source: Paul Edstein (Macropod), 8 Aug 2015: https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-search-and-replace-multiple-wordsletters-in/af4753a0-7afd-433b-910d-a148da66f2bf
' Original macro name: MultiReplace
' Adapted by Rhonda Bracey, Cybertext Consulting, 1 Sept 2023
' You could duplicate this macro with a different name (e.g. LegalWords [for must, shall, etc.]) using a different list of words in the StrFind and StrRepl lists

Dim StrFind As String
Dim StrRepl As String
Dim i As Long

' In StrFind and StrRepl, add words between the quote marks, separate with a comma, NO spaces
' To only highlight the found words (i.e. not replace with other words), either use StrRepl = StrFind OR use the SAME words in the same order in the StrRepl list as for the StrFind list; comment/uncomment to reflect the one you're using
' To replace a word with another and highlight it, put the new word in the StrRepl list in the SAME position as the word in the StrFind list you want to replace; comment/uncomment to reflect the one you're using

StrFind = "tion of ,ment of ,ent of ,ant of ,ancy of ,sion of ,ity of "
StrRepl = StrFind
Set RngTxt = Selection.Range

' Set highlight color - options are listed here: https://docs.microsoft.com/en-us/office/vba/api/word.wdcolorindex
' main ones are wdYellow, wdTurquoise, wdBrightGreen, wdPink
Options.DefaultHighlightColorIndex = wdTurquoise

Selection.HomeKey wdStory

' Clear existing formatting and settings in Find and Replace fields
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

With ActiveDocument.Content.Find
  .Format = True
  .MatchWholeWord = True
  .MatchAllWordForms = False
  .MatchWildcards = False
  .Wrap = wdFindContinue
  .Forward = True
  For i = 0 To UBound(Split(StrFind, ","))
    .Text = Split(StrFind, ",")(i)
    .Replacement.Highlight = True
    .Replacement.Text = Split(StrRepl, ",")(i)
    .Execute Replace:=wdReplaceAll
  Next i
End With
End Sub

 

When I ran this macro on just one 250p document, it found almost 100 different potential nominalisations—and many of these had been used often. Here’s the list I compiled from checking the highlighted phrases in that document, in case you want to add them to your own PerfectIt style sheet:

  • abandonment of
  • ability of
  • absorption of
  • acceptability of
  • acceptance of
  • accommodation of
  • accumulation of
  • acknowledgement of
  • acknowledgment of
  • acquisition of
  • action of
  • activation of
  • activity of
  • actuation of
  • addition of
  • adoption of
  • aggregate of
  • aggregation of
  • alignment of
  • allocation of
  • alteration of
  • amenity of
  • applicability of
  • application of
  • appreciation of
  • assessment of
  • assistance of
  • association of
  • attraction of
  • availability of
  • bioaccumulation of
  • biodegradation of
  • biodiversity of
  • biomagnification of
  • calculation of
  • calibration of
  • capability of
  • capacity of
  • cementation of
  • certification of
  • cessation of
  • characterisation of
  • collection of
  • combination of
  • combustion of
  • commencement of
  • commission of
  • commissioning of
  • commitment of
  • communication of
  • comparability of
  • compilation of
  • completion of
  • complexity of
  • compliance of
  • component of
  • composition of
  • concentration of
  • conclusion of
  • condition of
  • confirmation of
  • connection of
  • conservation of
  • consideration of
  • construction of
  • consultation of
  • consultation with
  • consumption of
  • containment of
  • contamination of
  • coordination of
  • corrosion of
  • creation of
  • criticality of
  • death of
  • declaration of
  • decommissioning of
  • decomposition of
  • definition of
  • degradation of
  • delegation of
  • demobilisation of
  • demonstration of
  • density of
  • depletion of
  • deployment of
  • deposition of
  • derivation of
  • desalination of
  • description of
  • detection of
  • deterioration of
  • determination of
  • development of
  • dilution of
  • direction of
  • disconnection of
  • discretion of
  • disorientation of
  • dispersal of
  • dispersion of
  • displacement of
  • disposition of
  • disruption of
  • dissemination of
  • distribution of
  • diversity of
  • duplication of
  • duration of
  • ecotoxicity of
  • employment of
  • enforcement of
  • enjoyment of
  • entanglement of
  • entrainment of
  • equipment of
  • eradication of
  • erosion of
  • eruption of
  • escalation of
  • establishment of
  • estimation of
  • evaluation of
  • evaporation of
  • excavation of
  • exception of
  • exclusion of
  • execution of
  • explosion of
  • export of
  • facilitation of
  • fatality of
  • formation of
  • formulation of
  • fragmentation of
  • fulfilment of
  • function of
  • functionality of
  • generation of
  • granularity of
  • identification of
  • impairment of
  • implementation of
  • import of
  • importance of
  • improvement of
  • inclusion of
  • independent of
  • indication of
  • inflation of
  • information of
  • ingestion of
  • initiation of
  • injection of
  • inspection of
  • installation of
  • integration of
  • integrity of
  • intensity of
  • intent of
  • intention of
  • interpretation of
  • intersection of
  • introduction of
  • investigation of
  • involvement of
  • irritation of
  • isolation of
  • judgement of
  • judgment of
  • jurisdiction of
  • legislation of
  • liability of
  • location of
  • lodgement of
  • lodgment of
  • maintenance of
  • majority of
  • management of
  • measurement of
  • misorientation of
  • mitigation of
  • mobilisation of
  • mortality of
  • movement of
  • multiplication of
  • navigation of
  • notification of
  • occupancy of
  • occupation of
  • occurrence of
  • oiling of
  • operation of
  • organisation of
  • orientation of
  • paucity of
  • payment of
  • placement of
  • pollution of
  • position of
  • possibility of
  • predation of
  • predication of
  • preparation of
  • prevention of
  • probability of
  • production of
  • productivity of
  • promotion of
  • promulgation of
  • propagation of
  • proportion of
  • protection of
  • provision of
  • proximity of
  • quality of
  • quantification of
  • quantity of
  • ration of
  • reaction of
  • re-certification of
  • recertification of
  • reduction of
  • re-establishment of
  • refurbishment of
  • regulation of
  • rehabilitation of
  • reinjection of
  • re-injection of
  • rejection of
  • replacement of
  • reproduction of
  • requirement of
  • resolution of
  • restriction of
  • retention of
  • revision of
  • salinity of
  • satisfaction of
  • sedimentation of
  • selection of
  • sensitivity of
  • settlement of
  • severity of
  • simplicity of
  • stabilisation of
  • stability of
  • statement of
  • submission of
  • subtraction of
  • supervision of
  • susceptibility of
  • suspension of
  • sustainability of
  • termination of
  • testing of
  • toxicity of
  • transportation of
  • treatment of
  • turbidity of
  • unavailability of
  • usage of
  • utilisation of
  • validation of
  • validity of
  • verification of
  • vicinity of
  • volatility of

For another way to do this, but instead changing the colour of a selected set of words (not highlighting them), see https://wordribbon.tips.net/T013773_Changing_the_Color_of_a_List_of_Words.html

[Links last checked September 2023]

h1

Word: Some macros won’t run

August 11, 2023

Here’s a new one to me… I have a couple of table formatting macros that I run on all tables in a document, but for some reason they wouldn’t run on a new client’s document. Instead I got this ‘Run-time error 4605’ message—the information varied according to what I was trying to do, but basically the different errors had the same number but slightly different text for the ‘method or property is not available because the current selection is locked for format changes’. I couldn’t find any relevant clues in Google.

I had NO idea what was causing this… until a day or so later when I checked some of the information in the front matter, where I found some content control boxes in certain table cells. I checked the properties of each (via the Developer tab) and some had a checkmark in the Contents cannot be edited checkbox.

I removed that checkmark, ran my macros successfully, then reset that property.

Update: This didn’t just affect my table macros, but also my ‘set language’ macros, which appeared to run, but didn’t change anything until I’d cleared those checkboxes. Also, I’ve now removed that checkmark fully as the client’s doc needed different info on the cover page, which I couldn’t add with those control boxes locked for editing..

h1

Word: Macro to convert one set of styles to another (revised)

January 23, 2023

A few years ago, I wrote a blog post about a VBA macro to convert one set of style names to another set of names in Word. One of my readers had an issue where the macro stopped running when it came across a situation where there was no existing style name that needed to be replaced with the new style name. I’d also come across this, but had ignored it and fixed up those mismatches manually.

But because I was asked the question, I used ChatGPT to see if it could offer a starting point for identify some VBA code that could ignore the ones not found. This gave my reader enough information to revise the macro for me (I don’t write VBA code; I can read it to a point and can record it or modify it, but that’s all). Their macro is much cleaner and doesn’t give an error where there’s no matching style name. It also pops up a message box when it’s finished running, which is a nice touch.

Some caveats:

  • Test first. Test on a COPY of the old document before doing it on the original copy, and any other documents in the set.
  • Make sure you’ve applied the new template to the old document so that the new styles are available in the document. (or, use the Organizer to copy styles across from the old template to the new [longer, slower method]).
  • Make a list of the old styles and the matching, but differently named, new styles—make sure you write down the style names EXACTLY (including capitalisation and any hyphens or underscores in the style name) otherwise those styles won’t change.
  • This macro runs a find and replace and replaces ALL. Test first.

If you want to use/modify this macro, copy/paste the code below–some of it runs off the page, so if you try to retype the code you may miss some critical command. Then modify each pair of Case and newStyleName lines to match YOUR style names (make sure you use double quotes around the style names). You can add as many of these pairs as you need.

Sub ConvertStyles()
'
' Converts old style names to new style names using find and replace
' Usage example: applying a template to a document where the style names
' for the same thing are different (e.g. now Table Bullet; was Table Bullet 1)

' From: Benjamin Abitan, based on macro from Rhonda Bracey, 11 Sept 2018: https://cybertext.wordpress.com/2018/09/11/word-macro-to-convert-from-one-style-to-another/,
' which was modified from https://stackoverflow.com/questions/29953322/changing-styles-in-word-using-vba [Christina]
' Tuned by Benjamin with the help of ChatGPT (21 Jan 2023).
' Rhonda Bracey converted the French to English and wrote some instructions (22 Jan 2023)

' Instructions: For each Case and newStyleName pair:
' add the old style name in double quotes in the Case line
' and the replacement style name (also in double quotes) in the newStyle Name line
' Set up as many of these pairs as you need.
' Note: The code for deleting the old style doesn't work, 
' but I commented it out and kept it in case someone figures that out.

 
Dim objDoc As Document
Dim StyleExists As Boolean
Dim s As Style

 
Set objDoc = ActiveDocument
 
For Each s In ActiveDocument.Styles
        'determine new style name
        Select Case s.NameLocal
            Case "Table Text - Left"
                newStyleName = "Table Text"
            Case "Table Bullet 1"
                newStyleName = "Table Bullet"
            Case "Table Head - Center"
                newStyleName = "Table Heading White"
            Case "Table Head - Left"
                newStyleName = "Table Heading White"
            Case "Table Text - Number"
                newStyleName = "Table Text Number"
            Case "App H1"
                newStyleName = "Appendix Heading"

            Case Else
                newStyleName = ""
        End Select
 
        If newStyleName <> "" Then
            With objDoc.Content.Find
                .ClearFormatting
                .Style = s.NameLocal
                With .Replacement
                    .ClearFormatting
                    .Style = newStyleName
                End With
                .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceAll
'                 ' delete old style
'                Do While .Found
'                    DoEvents
'                    .Execute
'                Loop
'                If s.BuiltIn = False Then
'                ActiveDocument.Styles(s.NameLocal).Delete
'                End If
            End With
        End If
    Next
 
MsgBox "Matching style names have been converted"
 
End Sub
h1

Word: Macro to show the Modern Comments pane and reduce its width

May 21, 2021

If you have Word 365’s new Modern Comments, you’ve probably figured out that they open by default in Contextual (floating) view and that there’s an option (on the Review tab) to change that to List view (i.e. a Comments pane docked to the right of the workspace). You may have also figured out that you can resize that window by dragging the vertical divider left (to make it wider) or right (to make it narrower). The size you select is carried over to any new documents you create in the same session, but not to documents you opened earlier, and is NOT remembered the next time you open Word. Which means you have to set this up again.

I created a macro that you can assign to a keyboard shortcut or Quick Access Toolbar icon that:

  • opens the Comments in List view (even if they were closed or were already displayed in Contextural or List view), AND
  • resizes the width of the Comments pane to a value you specify in the macro (in my macro, it’s 300, but experiment with this—I found 200 was too narrow for my laptop where I tested this, and 500 was too wide).
Sub CommentsPane()
'
' CommentsPane macro
' Opens the Modern Comments pane (List view) at the width specified
' Created by Rhonda Bracey, Cybertext Consulting Pty Ltd, 21 May 2021

    With Application.CommandBars("Comments")
        .Visible = True
        .Width = 300
    End With

End Sub

h1

Word: Batch convert old DOC documents to DOCX

November 22, 2020

I was going through some folders and found quite a number of Word files in DOC format that I created before I started using Word 2007, which was when the DOCX format was introduced. While I can open each and save it as DOCX, that becomes very tedious if you have more than a few to do. Off to the internet to see if there was a macro or other way of batch converting DOC files to DOCX files.

The two that offered the most promise were a macro from the makers of Kutools (https://www.extendoffice.com/documents/word/5601-word-batch-convert-doc-to-docx.html) and a converter program (http://www.multidoc-converter.com/en/index.html). I thought I’d try the macro first, and as it worked fine for what I wanted, I didn’t download and test the converter program.

Notes about the macro:

  • When testing, put the DOC files into a temporary folder and run the macro on that folder. You can copy the resulting DOCX files to the correct folder later. Once you are confident it works as expected, you could run the macro on the original folder.
  • Subfolders are ignored. The macro only works on the selected folder.
  • All the DOC files are opened briefly, then saved as DOCX, without your intervention. Let the macro run until it finishes.
  • All the new DOCX files will have the current date as the date of creation. All original date creation and modification information will be lost, and also possibly original author information (I didn’t check this).
  • If there are already DOCX files of the same name in the folder, this process will overwrite them automatically. This isn’t usually an issue, but if at some point you manually saved a DOC file as DOCX, then modified it, the converted DOCX file will overwrite that modified file. This is why it’s advisable to do these conversions in a separate folder to the original, then copy back once done.
  • If some of the DOC files are quite old, you may get a message that it cannot save Word 95 binary files (or similar), and the macro will not run. To include these documents in the conversion, got to File > Options in Word, then select Trust Center. Click Trust Center Settings, then go to File Block Settings. Uncheck the boxes for relevant file types that the macro got hung up on. Don’t forget to change this back later!

And in case that macro ever goes missing from the website linked above, I’ve pasted it here, with some additional comments. If you use this one, copy it all—do not retype it as several lines go off the page:

Sub ConvertDocToDocx()
' Opens all DOC files in a folder and saves as DOCX files
' Asks for the folder location of the DOC files when you run the macro
' If DOCX files of the same name exist in the folder, it will overwrite them
' Recommendation: Put DOC files into a separate folder and run there
' NOTE: Converted files will have today's date---original file date is lost forever

' From: by ExtendOffice 20181128
' From (22 Nov 2020): https://www.extendoffice.com/documents/word/5601-word-batch-convert-doc-to-docx.html

    Dim xDlg As FileDialog
    Dim xFolder As Variant
    Dim xFileName As String
    Application.ScreenUpdating = False
    Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
    If xDlg.Show <> -1 Then Exit Sub
    xFolder = xDlg.SelectedItems(1) + "\"
    xFileName = Dir(xFolder & "*.doc", vbNormal)
    While xFileName <> ""
        Documents.Open FileName:=xFolder & xFileName, _
            ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
            PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
            WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
            wdOpenFormatAuto, XMLTransform:=""
        ActiveDocument.SaveAs xFolder & Replace(xFileName, "doc", "docx"), wdFormatDocumentDefault
        ActiveDocument.Close
        xFileName = Dir()
    Wend
    Application.ScreenUpdating = True
End Sub

[Links last checked 22 November 2020]

 

h1

Word: Macro to find and highlight a set of specified words

February 22, 2020

This is a simpler version of a previous blog post—it doesn’t require you to set up and store a separate file of the words you want to highlight.

I wanted to create a list of vague words (such as some, most, often, frequently, sometimes—words that aren’t explicit or specific enough in technical writing and editing) that a simple Microsoft Word macro could find and highlight for me. I found some macros online that each partly solved the problem, and adapted one from Macropod (Paul Edstein) to suit my purposes as it was the closest to what I wanted. Full thanks to Macropod for this one.

There are several ways you can adapt this macro—I’ve commented some of my ideas in the code. I think the words are case sensitive, so if you want one with a capital (e.g. Some), you should add it as another entry.

NOTE: Copy all the code below to the clipboard—it goes off the page, so don’t type it out as you’ll miss some of it or could make a typo—then paste it into your VBA window.

Sub VagueWords()

' Source: Paul Edstein (Macropod), 8 Aug 2015: https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-search-and-replace-multiple-wordsletters-in/af4753a0-7afd-433b-910d-a148da66f2bf
' Original macro name: MultiReplace
' Adapted by Rhonda Bracey, Cybertext Consulting, 22 Feb 2020
' You could duplicate this macro with a different name (e.g. LegalWords [for must, shall, etc.]) using a different list of words in the StrFind and StrRepl lists

Dim StrFind As String
Dim StrRepl As String
Dim i As Long

' In StrFind and StrRepl, add words between the quote marks, separate with a comma, NO spaces
' To only highlight the found words (i.e. not replace with other words), either use StrRepl = StrFind OR use the SAME words in the same order in the StrRepl list as for the StrFind list; comment/uncomment to reflect the one you're using
' To replace a word with another and highlight it, put the new word in the StrRepl list in the SAME position as the word in the StrFind list you want to replace; comment/uncomment to reflect the one you're using

StrFind = "very,just,rarely,often,frequently,majority,most,minority,some,perhaps,maybe,regularly,sometimes,occasionally,best,worst,worse,better,seldom,few,many"
StrRepl = StrFind
' StrRepl = "very,just,rarely,often,frequently,majority,most,minority,some,perhaps,maybe,regularly,sometimes,occasionally,best,worst,worse,better,seldom,few,many"
Set RngTxt = Selection.Range

' Set highlight color - options are listed here: https://docs.microsoft.com/en-us/office/vba/api/word.wdcolorindex
' main ones are wdYellow, wdTurquoise, wdBrightGreen, wdPink
Options.DefaultHighlightColorIndex = wdTurquoise

Selection.HomeKey wdStory

' Clear existing formatting and settings in Find and Replace fields
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

With ActiveDocument.Content.Find
  .Format = True
  .MatchWholeWord = True
  .MatchAllWordForms = False
  .MatchWildcards = False
  .Wrap = wdFindContinue
  .Forward = True
  For i = 0 To UBound(Split(StrFind, ","))
    .Text = Split(StrFind, ",")(i)
    .Replacement.Highlight = True
    .Replacement.Text = Split(StrRepl, ",")(i)
    .Execute Replace:=wdReplaceAll
  Next i
End With
End Sub

For another way to do this, but instead changing the colour of a selected set of words, see https://wordribbon.tips.net/T013773_Changing_the_Color_of_a_List_of_Words.html

Update Oct 2020: A professor has made a YouTube video for his students/colleagues of this in action: https://www.youtube.com/watch?v=OIg95ETFxMQ

[Links last checked June 2020]

h1

Word: Macros to switch from No Markup to All Markup views

June 2, 2019

I worked on a 350p technical report the past two weeks, and was forever switching between No Markup (Final) view and All Markup (Final: Show Markup [i.e. track changes]) view. Moving the mouse to do that got old pretty quick, even though I have that control on my Quick Access Toolbar. What I needed was a keyboard command or two to flip between views. Well, I couldn’t find one! I couldn’t even find the command in the list of all commands. That’s not to say one doesn’t exist—just that I couldn’t find it. Update 5 June 2019: Angela, one of this blog’s subscribers, had a solution that she shared with me. I’ll leave the other macros in this post, but if you want one that just does it all in one toggle command, skip the information below and scroll down to the end under ‘Angela’s solution’.

What to do? Well, one way to get a keyboard shortcut it to create a macro that does what you want to do, and then assign a keyboard shortcut to it. That’s what I ended up doing, except I had to create two macros—one for showing and one for hiding the track changes (I couldn’t figure out how to create a ‘toggle’ macro that used the same command to turn on and off, depending on the current state). And I assigned these keyboard shortcuts that had some logic for me: Ctrl+Shift+{ (i.e. open the bracket) to show the markup, and Ctrl+Shift+} (i.e. close the bracket) to hide the markup. But you can use whatever shortcut that works for you.

The two macros I wrote are below. Once you’ve added them to you VBA area, assign a keyboard shortcut to them from the Customize Ribbon options area.

This macro shows all markup:

Sub MarkupViewAll()
'
' Shows All Markup view for markup (i.e. shows track changes)
' Created by Rhonda Bracey, CyberText Consulting, 31 May 2019
'
'
    With ActiveWindow.View
        .ShowRevisionsAndComments = True
        
    End With
End Sub

This macro shows the final view:

Sub MarkupViewFinal()
'
' Shows Final view for markup (i.e. hides track changes)
' Created by Rhonda Bracey, CyberText Consulting, 31 May 2019
'
'
    With ActiveWindow.View
        .ShowRevisionsAndComments = False
        .RevisionsView = wdRevisionsViewFinal
    End With
End Sub

I’m sure somebody cleverer with macros than me could write something more elegant (such as using the one macro and keyboard shortcut to toggle the view depending on the current view—if you know how to do that, feel free to contribute in the comments.

Angela’s solution

NOTE: Some of this macro goes off the page—to get it all, copy this macro, don’t retype it.

Sub ToggleMarkupViewAllToFinal()
' 
' Toggles from Markup view all to Markup view final
'
    ActiveWindow.View.ShowRevisionsAndComments = Not ActiveWindow.View.ShowRevisionsAndComments
    
End Sub

Thanks Angela! (by the way, I assigned Alt+m as my keyboard shortcut for this—it works a treat!

h1

Word: Macro to insert a landscape page

May 14, 2019

A client wanted an easy way for her staff to insert a landscape page into a report without messing up the headers and footers. I recorded a macro that does just that, but it relies on headers and footers being laid out using the alignment tabs, not borderless tables. Alignment tabs are much better than inserting tabs yourself as they automatically adjust if you change the page layout.

Note: If you use borderless tables for your headers and footers, this macro will still work, but you’ll have to manually turn off the Link to Previous options for the landscape page’s headers and footers and also for the following portrait page. I might see if I can tweak the macro to do that—if so, I’ll write it up as a separate blog post.

Step 1: Set up alignment tabs for the headers and footers

  1. Open a new Word document (or the template if you want to set this up in your template).
  2. Double-click in the header area to open the header. The cursor will be at the left margin.
  3. Optional: Add any text you want positioned at the left.
  4. In the Header & Footer Tools tab > Position group, click Insert Alignment Tab.
  5. By default the next position is Center. Make sure it’s selected, then click OK.
  6. Optional: Add any text you want positioned in the centre.
  7. Click Insert Alignment Tab again.
  8. Select Right then click OK.
  9. Optional: Add any text you want positioned at the right.
  10. In the Header & Footer Tools tab > Navigation group, click Go to Footer.
  11. Repeat steps 3 to 9 above for the footers.
  12. Double-click in the main body of the document to close the header/footer area.

Step 2: Install and run the macro

The macro you will use to insert a landscape section is listed below these steps.

  1. Go to the View tab >Macros group, then select View Macros from the drop-down list.
  2. In the Macro Name field, type InsertLandscape (if you have other macros listed, the one listed first will be in that field—just type over it)
  3. Click Create. This opens the Visual Basic for Applications (VBA) window, with these lines already inserted:
    Sub InsertLandscape()
    ‘ InsertLandscape macro
    End Sub
  4. Copy the macro below this set of steps.
  5. Paste it into the blank area above End Sub.
  6. Save the change and close the VBA window. (If you’re working in a template and only want this macro available to documents based on that template, then select the template name from the Macros in field.)
  7. Test the macro by running it:
    • Go to the View tab >Macros group, then select View Macros from the drop-down list.
    • Select the InsertLandscape macro.
    • Click Run.
  8. A landscape section should be inserted into your document, and the headers and footers should all align correctly for the landscape section.

Macro

' Inserts a landscape section, adjusts headers and footers
' Created by Rhonda Bracey, CyberText Consulting, May 2019
'
Selection.TypeParagraph
Selection.InsertBreak Type:=wdSectionBreakNextPage
Selection.TypeParagraph
Selection.TypeParagraph
Selection.InsertBreak Type:=wdSectionBreakNextPage
Selection.MoveUp Unit:=wdLine, Count:=2
If Selection.PageSetup.Orientation = wdOrientPortrait Then
Selection.PageSetup.Orientation = wdOrientLandscape
Else
Selection.PageSetup.Orientation = wdOrientPortrait
End If
ActiveWindow.ActivePane.SmallScroll Down:=-3
ActiveWindow.ActivePane.LargeScroll Down:=1

What this macro does:

  • Inserts an empty paragraph.
  • Inserts a Next Page section break.
  • Inserts two more empty paragraphs.
  • Inserts another Next Page section break.
  • Moves the cursor back up to one of the empty paragraphs between the two section breaks.
  • Changes the area between the section breaks to Landscape orientation.