Hide/show a specific page in VBA Word - vba

Hello I have a 2 pages word document with shapes and text boxes on each page. I would like to be able to hide the 2nd page or to show it.
I know we could hide a sheet on excel like bellow but I didn't find out how to do it in word :
Worksheets("Sheet1").visible = False
So I tried with this macro :
Sub HidePage2()
ActiveWindow.DocumentMap = True
Selection.Delete Unit:=wdCharacter, Count:=1
Selection.TypeBackspace
CommandBars("Navigation").Visible = False
End Sub
I thought I was hiding my page but in fact, it deleted it because if I replace the end of the code by the following code, it do not show my page number 2.
CommandBars("Navigation").Visible = True
I don't know how to fix my problem, could you help me?

Paragraphs and sections are Word VBA objects, pages are not. You can apply a bookmark to each group of paragraphs that you want to hide, plus the page break at the bottom of the page, if there is one. Then use code like this to show or hide it:
Sub HidePage2()
ActiveDocument.Bookmarks("Page2Bookmark").Range.Font.Hidden = True
End Sub
Sub ShowPage2()
ActiveDocument.Bookmarks("Page2Bookmark").Range.Font.Hidden = False
End Sub
Macropod's comment about the printer driver is relevant, because the pagination of the document can change if you have a different active printer. Then what you thought was on page 2 could partially be on page 1 or 3. You can minimise this problem by adding page breaks before and after page 2 and ensuring that page 2 is not completely full.

For example, without needing to bookmark the page beforehand:
Sub Demo()
ActiveDocument.Range.GoTo(What:=wdGoToPage, Name:="2").GoTo(What:=wdGoToBookmark, Name:="\page").Font.Hidden = True
End Sub

Related

Can VBA change pages in Microsoft Word's "Read Mode" Layout?

I'm trying to change pages while Microsoft Word is in "Read Mode"* by using a VBA code, and I can't seem to find any function that allows that.
(* Please notice that I'm talking about the "Read Mode" layout that you can change with the bottom-right icons in word, and not the "Read Only" mode that you sometimes get when you open a document from an unknown source)
In "Print Layout" it is simple since I can use something like -
Selection.GoTo What:=wdGoToBookmark, Name:="LastReadingPoint"
But It won't work while I'm in "Read Mode".
None of these work:
ActiveDocument.GoTo What:=wdGoToPage, which:=wdGoToAbsolute, Count:=1
ActiveDocument.Range.GoTo What:=wdGoToPage, which:=wdGoToAbsolute, Count:=1
Selection.GoTo What:=wdGoToBookmark, Name:="LastReadingPoint"
ActiveDocument.Range.GoTo What:=wdGoToBookmark, Name:="LastReadingPoint"
ActiveDocument.Range.GoToNext wdGoToPage
ActiveDocument.GoTo What:=wdGoToBookmark, Name:="LastReadingPoint"
(LastReadingPoint is a bookmark I've added to the text)
Any ideas or hacks?
Here are a few options, none of which are very good.
Use ScrollIntoView. This function scrolls so the provided range is visible somewhere on the screen. If the range is already on screen, nothing will happen. If it's off-screen, it seems to end up being positioned about 1/4 of the way down, similar to what happens when you follow a hyperlink.
ActiveWindow.ScrollIntoView ActiveDocument.Bookmarks("LastReadingPoint").Range
Follow an existing hyperlink within the document. This will position the target about 1/4 of the way down rather than at the top like the navigation pane or, in Word 2010, GoTo with a bookmark.
Dim h As Hyperlink
For Each h In ActiveDocument.Hyperlinks
If h.SubAddress = "LastReadingPoint" And h.Address = vbNullString And h.Type = msoHyperlinkRange Then
h.Follow
Exit For
End If
Next h
Create a new hidden document with a hyperlink to the bookmark and follow it. This requires your existing document to have been saved at some point so it has a name and path. It will also increment the counter used to name new documents.
Dim d As Document
Dim h As Hyperlink
Set d = Application.Documents.Add(Visible:=False)
Set h = d.Hyperlinks.Add(d.Range(0, 0), ActiveDocument.FullName, "LastReadingPoint")
h.Follow
d.Close False
Temporarily exit reading mode. The screen will flash and the ribbon will briefly appear, even if you turn off ScreenUpdating.
Dim readingMode As Boolean
readingMode = ActiveDocument.ActiveWindow.View.ReadingLayout
If readingMode Then ActiveDocument.ActiveWindow.View.ReadingLayout = False
Selection.GoTo wdGoToBookmark, , , "LastReadingPoint"
If readingMode Then ActiveDocument.ActiveWindow.View.ReadingLayout = True
After posting my answer, I was suggested with a superior answer.
My original answer:
At this point, I think that there is no way to control "Reading Mode" layout from VBA. Hence, I overcame this limitation by sending "Right arrow" key and "Left arrow" key to move one page forward and one page back respectively.
Private Sub BTN_IncPage_Click()
Word.Application.Activate
SendKeys ("{RIGHT}")
BTN_IncPage.SetFocus
End Sub
The superior answer:
source: https://social.msdn.microsoft.com/Forums/en-US/a5a198f4-f56c-4489-8ab4-3bb96db6a7f3/can-vba-change-pages-in-microsoft-words-8220read-mode8221-layout?forum=isvvba
ActiveWindow.ActivePane.PageScroll down:=1

VBA code for unhiding a bookmarked text is not working

I've created an ActiveX dropdown list and each option is linked to a bookmark for the text. Under the ActiveX controls there are the bookmarks (R1 andR2), hidden.
When I hit the btnselect button, all the other bookmarks, except the selected one, get deleted and the selected one becomes visible.
In the bookmark R2
I have a MacroButton for showing/hiding another text (CollapseMentiuniReclamant). When clicking the button it runs either Expand1 sub or Collapse1 sub, but the bookmark CollapseMentiuniReclamant doesn't show up.
I've simplified the document and codes as much as possible. Link to the document - https://wetransfer.com/downloads/1caea3c5d3b05e226e8b8f6a29760ad220190522071742/15db59.
The vba code is:
Private Sub btnselect_Click()
If ComboBox1.Value = "1" Then
Bookmarks("R1").Range.Font.Hidden = False
Bookmarks("R2").Range.Font.Hidden = False
Bookmarks("R2").Range.Delete
End If
If ComboBox1.Value = "2" Then
Bookmarks("R1").Range.Font.Hidden = False
Bookmarks("R1").Range.Delete
Bookmarks("R2").Range.Font.Hidden = False
Bookmarks("CollapseMentiuniReclamant").Range.Font.Hidden = True
End If
End Sub
Sub Expand1()
ActiveDocument.AttachedTemplate.BuildingBlockEntries("Collapse1").Insert _
Where:=Selection.Range
Bookmarks("CollapseMentiuniReclamant").Range.Font.Hidden = False
End Sub
Sub Collapse1()
ActiveDocument.AttachedTemplate.BuildingBlockEntries("Expand1").Insert _
Where:=Selection.Range
Bookmarks("CollapseMentiuniReclamant").Range.Font.Hidden = True
End Sub
Update: I've simplified the last part of code and the problem still persists:
Sub Expand1()
Bookmarks("CollapseMentiuniReclamant").Range.Font.Hidden = False
End Sub
I've even removed the button entirely and ran the macro from View Macros Tab and it's not working.
Why doesn't CollapseMentiuniReclamant show up?
It's not showing up because what you're trying to hide/unhide isn't inside the bookmarked range. In any event, you should be inserting/deleting the content, not simply toggling it's hidden property. Making something hidden is no guarantee it won't be seen or printed (even if not seen), as those settings depend on how the end user has Word configured.

Navigation Pane automation macro

I am trying to figure out a way to automate the navigation pane so that when you open a document, it automatically searches and shows results for all of the word comments in that document. The manual way to do this is to click the drop down arrow next to the navigation search bar, select comments under find and then select all reviewers. Is there a way to automate this?
Thanks!
Code below:
* The code works as it should but it does not actually display any comments. If you do this process manually, it will display all the comments in the document. If I use this macro, it will say no results found, even if the search bar has the same info. I've tried defining a range as the entire document but it hasn't worked.
Sub AutoOpen()
' Activate/Deactivate Navigation Pane
' Collapse All, to only show heading level 1
Set myRange = ActiveDocument.Content
ActiveWindow.DocumentMap = True
If ActiveWindow.DocumentMap = True Then
' Ctrl-F = Find --> this sets the cursor at the top of the navigation pane
' ^ = Ctrl key
' + = Shift key
SendKeys "^(f){TAB}{ENTER}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}
{ENTER}{DOWN}{ENTER}"
End If
ActiveWindow.View.ShowComments = True
End Sub
I'm not sure it is an exact answer to your question, but your attempt helped me find a creative way of using the new Word2016 navigation pane. I designed a userFrom to select special characters to be searched. In my case, to have navigation pane to display items, I had to dismiss the form and perform an ActiveDocuemnt.activate. Then and only then the navigation pane showed its results. Thanks.
DoEvents
Application.ScreenUpdating = False
' put text in word, copy to clipboard, and undo it
Dim s As Long
Dim e As Long
s = Selection.start
Selection.TypeText "the text I want to search that comes from my userform"
e = Selection.start
Selection.SetRange start:=s, End:=e
Selection.Copy
ActiveDocument.Undo
Application.ScreenUpdating = True
' make document map active
ActiveWindow.DocumentMap = True
' fortunately input field has focus, erase any content, paste
SendKeys "^(f){backspace}^{v}{Enter}"
Me.hide ' I hide my user form
ActiveDocument.Activate ' i activate the active document to see the result

Word 2010 VBA make a table and text disappear

I am working on a word document and made a command button that is suppose to hide a table. Now when I first set it, I thought I got it working I got it all styled and titled and when I clicked the button the table would disappear.
Then I saved it and closed the document but when I opened up the document I saw that the only thing that was hidden was the words inside the table, the table lines are not hidden and when I toggle the button the only thing hiding is the text.
Is there something I am doing wrong ? Here is the code in VBA
Private Sub CommandButton1_Click()
ThisDocument.Styles("HideText").Font.Hidden = Not ThisDocument.Styles("HideText").Font.Hidden
End Sub
I just want the button to toggle the text and the Table to hide every time it the button is pressed and when the document is open and closed.
Update may be on to something the table has its own style as well. should I be targeting that as well as the text within the style ? is that what is happening ?
Update #2
I was able to now hide and unhide the section of the table I wanted but it doesn't bring up the lines after I make the table visible. So is there a way to get the table grid to show up with the click of the button?
here is what I have so far.
Private Sub CommandButton1_Click()
ThisDocument.Styles("HideText").Font.Hidden = Not ThisDocument.Styles("HideText").Font.Hidden
'Table Grid
Dim s As Style
Dim An As Integer
An = 0
If An = 0 Then
For Each s In ActiveDocument.Styles
If s.Type = wdStyleTypeTable Then
If s.NameLocal = "Table Grid" Then
Debug.Print (s.NameLocal)
s.Visibility = False
s.UnhideWhenUsed = False
Call s.Delete
End If
End If
Next
An = 1
End If
If An = 1 Then
For Each s In ActiveDocument.Styles
If s.Type = wdStyleTypeTable Then
If s.NameLocal = "Table Grid" Then
Debug.Print (s.NameLocal)
s.Visibility = True
s.UnhideWhenUsed = True
Call s.Delete
End If
End If
Next
An = 0
End If
End Sub
I'd approach this by hiding the font of the table (as below) rather than attempting to hide a specific font style which you're using within the table.
You could try something along the lines of:
Public sub CommandButton1_Click()
With ActiveDocument.Tables(1).Range.Font
.Hidden = Not .Hidden
End With
End Sub

Insert highlighted sentence at bookmark in MS Word?

So I have a userform that I use to populate a template with text at certain bookmarks. To make it easy to see what text has been inserted, I would like it to be highlighted with yellow. Is there a convenient way to do this for every text that is inserted without typing it, selecting it and then highlighting it? As an example, this is what part of my code looks like atm:
With ActiveDocument
Options.DefaultHighlightColorIndex = wdYellow
'[highlight=yellow].Bookmarks("Modtager").Range.Text = TxtModtager.Value[/highlight]
.Bookmarks("Modtager").Range.Text = TxtModtager.Value
.Bookmarks("KSnr1").Range.Text = txtKSnr.Value
.Bookmarks("KSnr2").Range.Text = txtKSnr.Value
The first line doesn't seem to do anything - even without the option turned on new text is still not highlighted.
The second line is something I found at another site but had to be commented as it's not working.
The last three lines insert the actual text and I guess you could choose to select the bookmark first and then Selection.TypeText Text:="Whatever value I need", followed by selecting the new phrase again (how?) and choose .HighlightColorIndex = wdYellow.
There should be a better way though, any suggestions? :)
This works for me:
SetBkmkText "Modtager", TxtModtager.Value
SetBkmkText "KSnr1", txtKSnr.Value
SetBkmkText "KSnr2", txtKSnr.Value
Sub SetBkmkText(bkmk as String, NewText as String)
With ActiveDocument.Bookmarks(bkmk).Range
.Text = NewText
.HighlightColorIndex = wdYellow
End With
End Sub