VBA code not exiting list (MS Word) - vba

Writing a macro to automatically fix paraphrase spacing issues in MS Word docs generated from software we use.
Goal:
All standard paragraphs have 0pt before and after spacing.
All bullet lists have 3pt before and after spacing.
Progress:
Currently I have a function that sets the entire document to 0pt, then looks through for all lists and changes them to 3pt. (currently also have a highlight on so I can easily see what is being treated as a list).
It works great on some parts, but on other parts (I assume based on how the software we use generates the document), the list doesn't exist and it will continue to format blocks of text and heading to 3pt when it is not wanted (see attached images).
Current code is:
Sub Paragraph()
ActiveDocument.Range.ParagraphFormat.SpaceAfter = 0
ActiveDocument.Range.ParagraphFormat.SpaceBefore = 0
Dim li As Word.list
For Each li In ActiveDocument.lists
li.Range.ParagraphFormat.SpaceBefore = 3
li.Range.ParagraphFormat.SpaceAfter = 3
li.Range.HighlightColorIndex = wdYellow
Next li
End Sub
Working:
Not working:

According to the MSDN:
List Object: Represents a single list format that's been applied to specified paragraphs in a document.
So if you have more than one list with some non-bulleted paragraph(s) in the middle, the Range will start with the first item of the first list and end with the last item of the last list including all non-bulleted paragraph(s) in the middle.
To fix this issue, you need to separate the lists (right-click on the bullet and select Separate List). However, you mentioned that the document was generated by some software, so that is probably not an option. In that case, you will have to iterate though the paragraphs of the Range of each List and check if it has a ListFormat.ListTemplate which indicates that it is a list item, otherwise it is a non-bulleted paragraph:
Sub Paragraph()
ActiveDocument.Range.ParagraphFormat.SpaceAfter = 0
ActiveDocument.Range.ParagraphFormat.SpaceBefore = 0
Dim li As Word.List
Dim p As Paragraph
For Each li In ActiveDocument.Lists
For Each p In li.Range.Paragraphs
If Not p.Range.ListFormat.ListTemplate Is Nothing Then
p.Range.ParagraphFormat.SpaceBefore = 3
p.Range.ParagraphFormat.SpaceAfter = 3
p.Range.HighlightColorIndex = wdYellow
End If
Next p
Next li
End Sub

Even before touching VBA:
Use Styles in the document.
Limit the use of Styles in the document to only those that are in the
template.
Set your spacing in the Styles.
If, at some stage, you change your mind and want to use 6pt spacing, you can adjust the template and re-apply it, rather than finding all the VBA code and re-writing it. Not only that, but by using Styles, you can avoid having VBA code, or having VBA-enabled documents which may interfere with some corporate security settings.
Oh, and set up your corporate structure to limit the use of templates to only the approved ones.

Related

I'm trying to create a header that begins on the second page, inserts an em dash, the page number and another em dash, centered in vba

document.Application.ActiveDocument.Sections(1).Headers(WdHeaderFooterIndex.wdHeaderFooterPrimary) _
.PageNumbers.StartingNumber = 2
For Each section As Word.Section In document.Application.ActiveDocument.Sections
Dim headerRange As Word.Range = section.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
headerRange.Text = " — "
headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage)
headerRange.Text = headerRange.Text & " — "
Next
The issue that I am having is I cannot get the dashes on either side of the page number. It will always place both of them before or after the page number.
I have tried concatenating, I have tried various placements of the dashes. I have tried the headerRange.Collapse with no success.
'document.Application.ActiveDocument.Sections(1).Headers(WdHeaderFooterIndex.wdHeaderFooterPrimary) _
' .PageNumbers.StartingNumber = 2
'For Each section As Word.Section In document.Application.ActiveDocument.Sections
' Dim headerRange As Word.Range = section.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
' headerRange.Text = "—"
' headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
' headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
' headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage)
' headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
' headerRange.Text = "-"
'Next
To a man with a hammer, everything looks like a nail.
You are doing this the hard way, in my opinion.
I look at using a macro for this as reinventing the wheel - Instead, use Templates or Building Blocks
Perhaps I am lazy, but setting things up in vba and formatting it is hard, at least to me.
You could create a template with your header and use that as the basis for new documents. Here is my page on Templates in Microsoft Word.
You could save this as a Building Block if you want to use it in existing documents. Remember that using a page number building Block for top of page replaces any existing header, for bottom of page replaces any existing footer.
Here is a temporary link to a template containing three page number building blocks with those for top and bottom of the page being centered. All have M-dashes on either side. The font and size will be determined by the Header or Footer styles in the document. The template contains instructions for using it.
If you want to use vba to insert these building blocks, there are examples shown on my web page with specific instructions on placement of the macros and building blocks. Here is my answer here about using vba to insert a Table of Contents a Building Block.
You could also have a macro to create a new document based on your template.
No matter how you decide to do this, keep in mind that each Word section has three headers, whether or not they are seen. In multi-section documents, these may, or may not, be linked to like headers in previous sections.
Here is my recap of Header and Footer Settings.

VBA Word - iterate through all paragraphs in document in reverse

Problem in short:
I need to iterate through all paragraphs in reverse order. I am currently using a For Each loop:
For Each Paragraph in ActiveDocument.Paragraphs
' looping code
Next
Why I need to do this:
I have an export from a tool which incorrectly formats list elements. I need to go through and set all of these elements to the 'List' word style.
I have this part working using the various ListFormat properties on the paragraph. the problem is that the lists just continue, they dont retain when a list restarts. I end up with the list number being aaaaa. then bbbbb. etc.
I intended to use the ListFormat.ListValue property to determine when to restart the list (would restart when this value = 1), but this wont work, as when you transition one paragraph element to the new 'List' type, the following paragraph automatically resets the ListFormat.ListValue to 1 as well. If I can loop through paragraphs in reverse this will no longer be a problem.
Instead of using a For Each loop, iterate through the paragraphs by index, and you can easily loop from the last paragraph to the first with Step -1.
Sub Test()
Dim i As Long
For i = ActiveDocument.Paragraphs.Count To 1 Step -1
ActiveDocument.Paragraphs(i).... ' do whatever you want with each paragraph
Next i
End Sub

How to choose a different header image in MS Word 2013 using a macro/button

I'd like to create a Word stationary template with ability to cycle through different colored logos in its header. My company uses a logo in five different colors and I would like to create a single template with a button that would allow me to cycle through the different colored logos every time I create a new document from this template. Can this be done, perhaps with a little VBA?
Edit:
After working with an answer from Olle Sjögren I've come up with the following working script:
Option Explicit
Public imgCounter As Integer
Sub cycle_logos()
Dim I As Variant
Dim logoColors(4) As String
logoColors(0) = "logo_magenta.png"
logoColors(1) = "logo_teal.png"
logoColors(2) = "logo_orange.png"
logoColors(3) = "logo_red.png"
logoColors(4) = "logo_grayscale.png"
For Each I In logoColors
ActiveDocument.StoryRanges(wdPrimaryHeaderStory).ShapeRange.Item(I).Visible = msoFalse
Next I
imgCounter = imgCounter + 1
If imgCounter = 5 Then imgCounter = 0
ActiveDocument.StoryRanges(wdPrimaryHeaderStory).ShapeRange.Item(logoColors(imgCounter)).Visible = msoTrue
End Sub
It is worth mentioning how I came up with the image names, since I didn't find a way to do this from inside Word. I renamed the template extension to zip and unzipped it. In the extracted files I opened word\header2.xml (this may vary, depending on the position in the document) and edited the nodes containing the names of pictures, i.e. <wp:docPr/>, e.g.:
<wp:docPr name="Picture 1" id="1"/>
became:
<wp:docPr name="logo_magenta.png" id="1"/>
etc. I then replaced the XML file in the ZIP with my edited version and changed the extension back to dotm.
As mentioned, there are several ways to do this. I would suggest storing the images outside of the template, otherwise all documents based on the templates would include all logo images, even if they are not shown, making the documents bigger than they need to be. That approach makes installing the template a bit harder, since you would have to copy the images to the clients as well as the template file.
To answer your question regarding addressing the images in the header - you can address then through the correct story range object. In my example I assume that they are in the primary header. To tell the different images apart, you can use the Name property or the index in the Item collection:
ThisDocument.StoryRanges(wdPrimaryHeaderStory).ShapeRange.Item("Picture 1").Visible = msoTrue
ThisDocument.StoryRanges(wdPrimaryHeaderStory).ShapeRange.Item(1).Visible = msoFalse

Word Macro to convert Bullets into simple Text

I am looking a way to convert the Bullets in Word document to simple text. E.g.
I have these kind of Bullets:
a)-> Apple
b)-> Orange
c)-> Mangoes
I want them to be like this:
a)Apple
b)Oranges
c)Mangoes
I am using this code but it removes the Bullets entirely:
Dim oPara As Paragraph
For Each oPara In ActiveDocument.Paragraphs()
Set r = oPara.Range
If r.ListFormat.RemoveNumbers = wdListBullet Then
r.ListFormat.ApplyListTemplate _
ListTemplate:=ListGalleries(wdNumberGallery) _
.ListTemplates(1)
End If
Set r = Nothing
Next
Is ActiveDocument.ConvertNumbersToText what you're after?
It can also be run on a specific list if you're not doing this globally.
ETA: It seems like ConvertNumbersToText takes a NumberType argument (this isn't documented by the 2010 spec that F1 brings up, but it is valid). Perhaps the default doesn't apply to all the bullets in your document. A combination of the three possibilities might work.
ActiveDocument.ConvertNumbersToText(wdNumberParagraph) 'Preset numbers you can add to paragraphs by selecting a template in the Bullets and Numbering dialog box.
ActiveDocument.ConvertNumbersToText(wdNumberListNum) 'Default value for LISTNUM fields.
ActiveDocument.ConvertNumbersToText(wdNumberAllNumbers) 'Default value for all other cases.
I tend to use the first one, but your case might be different.

Finding the Outline Level of a Office 2010 Word Document using VBA

I'm creating a VBA macro that will validate a submitted document, but I can't seem to find a way to check for the Outline Level of the document as a whole. What I need is a way to tell the outline level selected in the Outlining Ribbon, 1-9 or All Levels.
The setting you are after is an application setting which is not stored in the file.
You can set a specific level using the following VBA code:
ActiveWindow.ActivePane.View.Type = wdOutlineView
ActiveWindow.View.ShowHeading 6
The .OutlineLevel property of a Word document can apply to the Paragraph, ParagraphFormat or Paragraphs Collection objects. It is an enumeration that can take the values wdOutlineLevel1 - 9, or wdOutlineLevelBodyText.
To find the OutlineLevel of the first paragraph in the document, use:
Dim currOutlineLevel
With ActiveDocument
currOutlineLevel = .Paragraphs(1).OutlineLevel
End With
Note that calling Paragraphs(x).OutlineLevel errors if called with the active doc in Outline view which makes iterating an Word outline for export rather a bore. You have to toggle the view (which also doesn't appear to be directly scriptable) then toggle back. Hope that saves someone else wasting time...