VBA: Word 2013 Expand/Collapse Specific Headings - vba

I need help, and I think this is pretty easy if you know VBA:
I want to have a button or dropdown menu that expands/collapses specific menu headings.
Here is an outline of the layout of the document (there are menus and data within the Department levels as well, but I don't need to collapse/expand those levels):
- Daily Processes
Department A
Department B
Department C
Department D
- Weekly Processes
Department A
Department B
Department C
Department D
- Monthly Processes
Department A
Department B
Department C
Department D
- Annual Processes
Department A
Department B
Department C
Department D
- Appendix
I want there to be buttons for each department, hiding all other departments. For example, if I click Department A, all Dept B, C, D menus will collapse, only showing Dept A.
I would imagine these would be the buttons that I would need:
ExpandAll
ShowDeptA
ShowDeptB
ShowDeptC
ShowDeptD
This is the pseudocode for one dept that I think would work:
ExpandAll
Start at top of Document
Search Format=Heading2
If Heading2=DepartmentA: expand heading,
Else: collapse heading
What I have so far: (All I need the command to collapse headings)
Sub OpenDeptA()
'
' OpenDeptA Macro
' Show only DeptA sections
'
' Expand all menus
ActiveDocument.ActiveWindow.View.ExpandAllHeadings
' Move cursor to the top
Selection.HomeKey Unit:=wdLine, Extend:=wdExtend
Selection.HomeKey Unit:=wdStory
' Find first menu using format: Heading 2
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Execute
' Loop through document collapsing heading if not equal to "DeptA"
Do Until Selection.Find.Found = False
If Selection.Text = "DeptA" Then
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Execute
Else: Selection.CollapseHeading ***NOT SURE HOW TO COLLAPSE MENUS***
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Execute
End If
Loop
End Sub

I don't have Word 2013, so I can't provide a complete answer. But I can help with two aspects of what you are doing.
Comparing text. Right now you are comparing just words "Dept A", but it is likely that the actual selection contains the line break as well. You could try
Selection.Text = "DeptA" & vbCR
or
Selection.Text Like "DeptA*"
It depends a bit on how tightly controlled those headings are.
Collapsing the content. I assume you are already putting the document into Outline View. If so, the command is
ActiveWindow.View.CollapseOutline Selection.Range
the thing about CollapseOutline, though, is that it only collapses by one level. So if you had a Heading 3 under your Heading 2, that would be collapsed but your Heading 2 would not be. From what I can tell there's no harm in running CollapseOutline several times, so I'd work out ahead of time how deeply the levels in your document go and then run the method enough times to accommodate that.
Ok, revisiting this with a copy of Word 2013 in front of me. There doesn't seem to be a method for collapsing the text; instead, you set its collapsed state to true. And, it works on paragraphs, not ranges or selections. So here is the final portion of your code, with the collapsing code included:
Do Until Selection.Find.Found = False
If Selection.Text Like "Department A*" Then
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Execute
Else: Selection.Paragraphs(1).CollapsedState = True
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Execute
End If
Loop
As to your question about Word Commands that you can see in the Macros list, you can run these, but their real power lies in the ability to recode them to do what you prefer. In this case what you need to do is supported by the object model so I wouldn't bother with them.
Lastly, if you intend to do a lot of VBA coding, I'd recommend getting familiar with the Object Browser (F2 from the VB Editor). You can search for something you think might exist there; for instance, in looking into this question I searched for "Collapseheading". In this case that wasn't fruitful on its own, but it did put me in the neighborhood of CollapsedState.
Hope this helps.

Related

VBA-Word bug: Undo list get error if use UndoRecord to record "Replace All" while there is a "Apply Quick Style" in the undo list. How to avoid?

On Word window, do something like typing, format font, paragraph... to ensure the undo list is not empty, and then change style of some text by clicking any Style on Ribbon. An entry named "Apply Quick Style" appear in the undo list. Then run macro like:
Sub SampleMacro()
Dim myUndoRecord As UndoRecord
Set myUndoRecord = Application.UndoRecord
myUndoRecord.StartCustomRecord ("VBA - Format Text")
'I do a lot of step here, but for this example, just simple like below
Selection.Characters(1).Bold = True 'just for example
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "Find Text"
.Replacement.Text = "Replace Text"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
'Word undo list get error after below step
Selection.Find.Execute Replace:=wdReplaceAll
'no crash, no error message, but the entry "Apply Quick Style"
'become to "Replace All", and Word can't go back before that entry
myUndoRecord.EndCustomRecord
End Sub
After this line of code:
Selection.Find.Execute Replace:=wdReplaceAll
The entry named "Apply Quick Style" in the undo list will become to "Replace All" and I can't undo (by press Ctrl-Z, or click arrow button on Quick Access Toolbar) to go back any step before that entry "Replace All". It's allway appear in undo list and Word will not go back anymore.
How to avoid this bug?
I'm using Word 2016 pro 64 bit
Additional information: using copy paste by press Ctrl+C, Ctrl+V (from other document to current document) instead of "Apply Quick Style" also get error, the entry "Paste" in undo list also rename to "Replace all". The different is still able to go back before that entry. Maybe there is another way will get error if use UndoRecord to record "Replace all".
Update 10/01
A working work around
The problem is specific to wdReplaceAll. If that specific wdConstant is omitted or replaced then "Apply Quick Style" will not be renamed and the undo stack remains accessible.
Lucky for us, Find.Execute returns a Boolean value (True for success). That means, we can loop with wdFindOne to replace all matches and use .Execute = False as the exit condition.
Add the word Do above your With block and replace the line with .Execute.
Do
With Selection.Find
[....]
End With
Loop While Selection.Find.Execute(Replace:=wdReplaceOne)
A word of caution: some circumstances will create an infinite loop (such as replacing "A" with "A"). As such, you should consider using a second exit condition or replacing wdFindContinue with wdFindAsk or wdFindStop.
Update 9/30
(Edit 10/01) Oops!! The Apply Quick Style entry was not renamed (good) but I wrongly assumed the undo stack could be reached when the same limitation exists (bad). Also, testing today, I learned there is a third condition: .Execute must not find any matches (worse). Suffice it to say, this is an exemplary demonstration of how not to test a solution, I hope everyone learned thier lesson!
When I create a new document and follow your steps, I can consistently reproduce the issue you describe. Thank you for making that easy!
As much as I am able to replicate the problem, I am also able prevent it by meeting two conditions.
Ensure Replace All is listed in the Undo Stack above Apply Quick Style.
Replace All is applied to the entire document (the problem persists if Replace All is applied to a Selection within the document)
This method worked regardless if it was done manually with 'Ctrl + H' or if it was part of a macro. Replacing a character with the same character was sufficient.
A screenshot showing the execution point after the problematic line:
The Undo Stack contains an intentionally placed Replace All to preserve Apply Quick Style.
This article is for Excel but it's relevant for Word.
https://excel.tips.net/T002060_Preserving_the_Undo_List.html
In short, you're on your own.
You have two options: revert to a previously saved version; or, write a macro that mimics Undo and ensure this macro is running before you start the one that messes with the Undo list

Reduce Myrange from paragraph into two lines

After setting Myrange of the first paragraph. I need to evaluate number of lines of current paragraph, if lines are less then 3 then following code will turn font into bold.
Set Myrange= Selection.Range.PARAGRAPHS(1).Range
If Myrange.ComputeStatistics(wdStatisticLines) < 3 Then
Myrange.Font.Bold = True
Else
Set Twolines = myrange.Duplicate
'''Here I want to reduce Myrange to only 2 lines
End If
so my question is how can I change Myrange from paragraph into 2 lines?
I had been doing this by Selection method and don't know how to perform it using Ranges. e.g.
Selection.ExtendMode = True
Selection.EndKey Unit:=wdLine
Selection.MoveDown Unit:=wdLine, Count:=2
The approach you have, using the Selection object, is really the only way.
"Lines" and "pages" in a Word document have no corresponding objects in the Word object model. Unlike Words or Paragraphs, for example, lines and pages are "dynamic": where a line or page break occurs depends totally on how Word's layout engine, in concert with the current print driver, processes the document in a particular session. It's quite possible that a line or page break is different on one computer than on another. And they will certainly change "fluidly" as a document is being edited.
For this reason, it's not really possible to deal with a line or a page as an "object" in the progamming sense of the term. That's why it's only possible to deal with these by using Selection.

Cross reference to custom reference type

I'm trying to add a cross reference into a SEQ field.
My document contains "point headings" which means that between two heading elements, the user can add an extension (between 1.1 and 1.2 may be 1.1A, 1.1B, ...)
Here is how the point heading code looks like:
{STYLEREF "HEADING 2" \N}{SEQ "HEADING 2 POINT" \* ALPHABETIC \S 2}
Which results with: 1.1A
I want to be able to do a cross reference into the point heading.
While I can set the reference type into 'Heading' I can't find out how to reference it to a custom element.
Searching through the web did not reveal any solution but some clues that it might be possible:
This website which explains cross-reference formatting, contains an image with custom type (My New Caption).
Microsoft DOC's description for ReferenceType is: The type of item for which a cross-reference is to be inserted. Can be any WdReferenceType or WdCaptionLabelID constant or a user defined caption label.
My client is used to work with the cross reference dialog box hence I prefer this approach, but VBA script will also be appreciated.
Thanks!
Update:
I'll try to describe my constraints and environment.
Headings 1-9 are used inside Multi-Level list item, hence they have custom styling.
They cannot be changed.
For a specific task, which is described and answered here, I've created what I call 'Point Headings'.
'Point Headings' are basically an extension that the user can add in between the Multi-Level numbering with a VBA macro.
Let's say that I have two Heading 2 items (1.1, 1.2), the user can add 1.1A, followed by 1.1B and so on.
The user can add point headings from level 2 up to level 5.
Their style is 'Heading 2 Point', 'Heading 3 Point' and so on, and each one is based on its relevant Heading.
As described above, eventually in the document, the word field has the following structure: {STYLEREF "HEADING 2" \N}{SEQ "HEADING 2 POINT" \* ALPHABETIC \S 2}.
My goal is to be able to cross reference into these items, but they do not appear in the Heading type, well because they are not of style Heading.
I wish to be able to create a custom reference type, which will show these items.
After some research, here is my answer. Hopefully it will help some future viewers.
Private Sub createPointHeader(pointLevel As Integer, Optional appendixPrefix As String = "")
Dim sQuote As String, referencedStyle As String, captionName As String
sQuote = Chr(34)
referencedStyle = appendixPrefix & "Heading " & pointLevel
captionName = referencedStyle & " Point"
With Selection
.Fields.Add .Range, wdFieldEmpty, "StyleRef " & sQuote & referencedStyle & sQuote & " \n", False
.Collapse wdCollapseEnd
CaptionLabels.Add (captionName)
.InsertCaption Label:=captionName, ExcludeLabel:=True
' Select the created field
.MoveLeft Count:=1, Extend:=True
' Replace the syntax from Arabic to Alphabetic
.Fields.ToggleShowCodes
With .find
.Text = "ARABIC"
.Forward = False
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
If .Found = True Then
Selection.Range.Text = "ALPHABETIC \s " & pointLevel
End If
End With
.Fields.ToggleShowCodes
.Fields.Update
.MoveRight Count:=1
.InsertAfter vbTab
.Collapse wdCollapseEnd
' Apply style after .InsertCaption, because it changes the style to Caption
.Style = ActiveDocument.Styles(referencedStyle & " Point")
End With
End Sub
Few remarks
I have two styles to base upon: Heading (2-5), and Appendix Heading (2-5). This is the reason for the optional appendixPrefix as a sub variable.
CaptionLabels.Add as I've checked can get the same value. No need to check in advance if it already exists.
Selection.InsertCaption automatically changes the style into Caption. This is why I apply the style change at the end.
The result
Here is how Point Heading 2 looks like:
{STYLEREF "HEADING 2" \N"}{SEQ HEADING_2_POINT \* ALPHABETIC \S 2}
Snapshot of the document with the point headings
And finally, as requested, cross reference to the Point headings from the Cross reference box
The question asks how to create a cross reference to a custom reference type. I suspect this answer may actually respond to what the original asker might have been getting at.
The idea is to use custom caption labels. A custom caption label appears (ideally) in the Insert/Cross Reference dialog.
A custom caption label is created when you say Insert/Caption and then ask to add a new custom label.
If you have added a custom caption label yourself in a given document, then it automatically appears as a choice when you say Insert/Cross Reference ...
However a difficulty arises when you are given a document where someone else has already added the cross reference type and you want to edit it (by adding additional cross references to the given type of caption). The secret here is to add the custom caption label yourself (even though it already exists), by creating a new temporary caption with the custom label type. You can then go ahead and delete the temporary caption, but you will from then on be able to add cross references to that caption type.
I use this when I want to make reference to 'Code Snippets' or 'Boxes' or 'Algorithms'.
I'm taking the chance of responding as an answer rather than as a comment as the reply is longish but hopefully should get you going in the right direction.
I think you have been led down the wrong path by the point pages article you have referenced.
I'm assuming that we can't modify the styles 'Heading 1' to 'Heading 9'. If you can then you will be able to adapt the suggestion below to use with only 'Heading 1' to 'Heading 9' styles.
You will need to create some new styles. I've used the following styles
Name Based on Style Outline level
Heading Point 1 Heading 1 1
Heading Point 2 Heading 2 2
Heading Point 2 Ext Heading 2 3
Heading Point 3 Heading 3 4
Heading Point 3 Ext Heading 3 5
Heading Point 4 Heading 4 6
Heading Point 4 Ext Heading 4 7
Heading Point 5 Heading 5 8
Heading Point 5 Ext Heading 5 9
Please note that getting the outline level correct is important for Heading numbering.
Next create a new Multilevel list. Call the list 'PointNumbering' (Because if you do this you can identify the list by the name in VBA should you need this facility). Link the styles 'Heading Point 1' to 'Heading Point 5 Ext' to levels 1 to 9 of the numbering sequence (e.g. Outline level 1 matches level 1 in the numbering sequence etc).
Turn off the legal style numbering for each level otherwise we won't be able to use Alphabetic numbering. Set the numbering scheme as indicated below.
Level Number style format levels* Final Appearance
1 1,2,3, 1 1
2 1,2,3 1.2 1.1
3 A,B,C 1.23 1.1A
4 1,2,3 1.2.4 1.1.1
5 A,B,C 1.2.45 1.1.1A
6 1,2,3 1.2.4.6 1.1.1.1
7 A,B,C 1.2.4.67 1.1.1.1A
8 1,2,3 1.2.4.6.8 1.1.1.1.1
9 A,B,C 1.2.3.6.89 1.1.1.1.1A
The actual levels are picked from a drop down list and appear as '1' in the number format box. This makes getting the numbering wrong quite easy so take care. The last number in each level is obtained by selecting the number format in the 'Number style for this level' box.
Once you have set up your styles and ensured that they are linked to the above numbering scheme you need to adjust the styles used for the headings in you current document.
Do a search and replace to do the following style replacements
Current Style New Style
Heading 1 Heading Point 1
Heading 2 Heading Point 2
Heading 3 Heading Point 3
Heading 4 Heading Point 4
Heading 5 Heading Point 5
Then for each of your extension headings where you are currently creating the numbering using style ref and seq field delete the fields and apply the relevant Ext Heading.
Thus for A,B,C numbering after 'Heading Point 2', apply the 'Heading Point 2 Ext' style.
This should now mean that all Heading Point styles can be accessed through the cross reference dialog.
If you document headings at 'Heading 6' Level 6 and below the after 'Heading Point 5 Ext you can use the Heading styles (Heading 6 to Heading 9) as normal. However, each time you use a Heading 6 you will need to manually reset the number. I think this is an easier task than asking users to insert multiple styleref and seq fields because you just select then right click on the heading number and then tick buttons to enable 'Advanced value (skip number)' which allows you to reset any level within your current Heading Number.
If you subsequently need to create a TOC field for your document you will now have to use the \t switch and provide a list of styles and the level number to use for the style in the TOC. e.g. {toc \t "Heading Point 1,1,Heading Point 2,2,Heading Point 2 Ext,2,Heading Point 3,3,Heading Point 3 Ext,3.....etc}.
I have created and tested all of the above in a Word document.

Looping through the parts of a non-contiguous selection in MS *Word* VBA

I have a macro in MS Word 2013 VBA (not Excel) that toggles the selected text's highlight color. Code looks like
this:
If Selection.Range.HighlightColorIndex = WhtColor Then Selection.Range.HighlightColorIndex = wdNoHighlight Else Selection.Range.HighlightColorIndex = WhtColor
That works great for continuous/contiguous selections. But, if I
select, say, 4 non-contiguous rows in a Word table (say, rows 5, 12,
15, and 19), the macro highlights only the last row selected.
How do I get the HighlightColorIndex to apply to all "parts" of the
noncontiguous range, or, how do I loop through the different "parts"
of the range and apply the HighlightColorIndex to each part?
The web page that Tim Williams points to (support.microsoft.com/en-us/kb/288424) gives a clue about how this is possible. But, that link does show that one cannot loop through a non-contiguous selection.
Nevertheless, what that link also shows is that Font formatting can be set for a non-contiguous selection, but not for a range object.
Here is the revised code that does work for a non-contiguous selection:
If Selection.Font.Shading.BackgroundPatternColor = WhtColor Then Selection.Font.Shading.BackgroundPatternColor = wdColorAutomatic Else Selection.Font.Shading.BackgroundPatternColor = WhtColor
That code will change the background color to the target color selected (although I had to change the color codes from Wd constants to WdColor constants).
The only drawback with this approach is that I do not know a way to search for text whose background color has been changed, whereas you can search for text that is highlighted.
Anyway, thanks, #Tim Williams for the helpful link. Hope the above helps someone else who just wants to change font properties and does not actually have to loop through the separate pieces of the selected range.

How do I apply a style to multiple selections in Word using VBA?

I created a macro that will apply a particular style to whatever is selected in the document. However, when in draft view, when the user clicks in the style area pane to select a paragraph and then Ctrl + clicks on an additional paragraph, this additional selection is not applied when this macro is run:
Sub BodyTextApply()
Selection.Style = ActiveDocument.Styles("Body Text,bt")
End Sub
What do I need to add to this? Note: The workflow cannot change so that the user selects that actual text in the document; they are set on using the style area pane...
The workflow is as follows:
alt text http://img6.imageshack.us/img6/1994/91231840.png
The (undesired) output is as follows:
alt text http://img34.imageshack.us/img34/1239/outputt.png
Looks like your style "Body Text,bt" is a pure paragraph style. That means it will only be applied to a complete paragraph.
However, in your screenshot there is only part of the second paragraph selected. Make sure the complete paragraph is selected or, if the style should only be applied to part of the paragraph, make your style "Body Text,bt" a linked (paragraph and character) style.
Programmatic access to discontiguous selections is very limited, and such selections can only be created using the Word UI. The MSDN article Limited programmatic access to Word discontiguous selections gives some more details.
If applying the style only to part of the paragraph (by making it a linked style) is not what you want you probably have to come up with a hack like this:
Sub BodyTextApply()
Dim oRange As Range
' create a temporary character style
ActiveDocument.Styles.Add "_TEMP_STYLE_", wdStyleTypeCharacter
' apply the temporary style to the discontiguous selection
Selection.Style = ActiveDocument.Styles("_TEMP_STYLE_")
Set oRange = ActiveDocument.Range
With oRange.Find
.ClearAllFuzzyOptions
.ClearFormatting
.ClearHitHighlight
.Style = ActiveDocument.Styles("_TEMP_STYLE_")
.Text = ""
.Wrap = wdFindStop
' search for all occurences of the temporary style and format the
' complete paraphraph with the desired style
Do While .Execute
oRange.Paragraphs(1).Style = ActiveDocument.Styles("Body Text,bt")
Loop
End With
' cleanup
ActiveDocument.Styles("_TEMP_STYLE_").Delete
End Sub
You probably want to add some error handling as well to make sure that the temporary style used is finally removed from the document.