I am trying to insert a new page in word i.e insert a section break. The problem is that i want to change this page to A3 landscape and remove all headers, which my code currently does not do. How to modify my code below to achieve this?
Below is my current code that insert new page, but keeps the header and a4 portrait:
If wordDrawingExist Then
Selection.EndKey Unit:=wdStory
Selection.InsertFile FileName:=wFile, link:=False
Set wb = Documents.Open(wFile)
Selection.WholeStory
Selection.Copy
Documents(docLogSkjema).Activate
Selection.EndKey Unit:=wdLine
Selection.InsertBreak Type:=wdPageBreak
Selection.Paste
wb.Close False
End If
wFile is fullpath to a wordfile, which is basically a pdf to word from freepdfsolutions.com (Tried inserting the pdf directly but then the quality of the pdf was so bad that numbers were hard to read) and wordDrawingExist is the boolean saying if the wordfile exist or not
OK, first of all, you will need a section break, not a simple page break:
Selection.InsertBreak Type:=wdSectionBreakNextPage
To change to landscape orientation:
Selection.PageSetup.Orientation = wdOrientLandscape
Make sure you are in the section you want to change. Note that after inserting the section break, the cursor will be in the new section.
To change the size to A3, you will need to set the size manually:
With Selection.PageSetup
.PageWidth = CentimetersToPoints(42)
.PageHeight = CentimetersToPoints(29.7)
End With
To delete the header:
selection.Sections(1).Headers(wdHeaderFooterPrimary).Range.Delete
Your selection doesn't include multiple sections, so from the one section it touches, you need the first (duh) hence the Sections(1).
Put it all together:
Selection.InsertBreak Type:=wdSectionBreakNextPage
With Selection.PageSetup
.Orientation = wdOrientLandscape
.PageWidth = CentimetersToPoints(42)
.PageHeight = CentimetersToPoints(29.7)
End With
Selection.Sections(1).Headers(wdHeaderFooterPrimary).Range.Delete
This code will insert a new section+page break, set this new section to landscape A3, and remove the headers from it.
Note: You might need to unlink the headers before deleting it:
selection.Sections(1).Headers(wdHeaderFooterPrimary).LinkToPrevious=False
Hope this helps.
Here is the working code in case someone else also find it useful:
'Add drawing
If wordDrawingExist Then
Set wb = Documents.Open(wFile)
Selection.WholeStory
Selection.Copy
Documents(docLogSkjema).Activate
Selection.EndKey Unit:=wdStory
Selection.InsertBreak Type:=wdSectionBreakNextPage
With Selection.PageSetup
.Orientation = wdOrientLandscape
.PageWidth = CentimetersToPoints(42)
.PageHeight = CentimetersToPoints(29.7)
End With
Selection.Sections(1).Headers(wdHeaderFooterPrimary).LinkToPrevious = False
Selection.Sections(1).Headers(wdHeaderFooterPrimary).Range.Delete
Selection.Sections(1).Footers(wdHeaderFooterPrimary).LinkToPrevious = False
Selection.Sections(1).Footers(wdHeaderFooterPrimary).Range.Delete
Selection.Paste
wb.Close False
End If
Related
I asked how to replace the space at the end of a line with a non-breaking space if the preceding character is a digit, throughout the document.
The code below makes my Word crash when it highlights the last line of the second last page of the document.
Dim myRange As Range
Set myRange = ActiveDocument.Range(ActiveDocument.Range.Start, ActiveDocument.Range.Start)
myRange.Select
Selection.Expand wdLine
While Selection.End < ActiveDocument.Range.End
If Right(Selection.Text, 1) = " " And IsNumeric(Left(Selection.Words.Last, 1)) = True Then
Selection.Characters.Last = Chr(160)
End If
Selection.MoveDown wdLine, 1
Selection.Expand wdLine
Wend
I suspect that you have your document in Print Layout view. Changing to Draft view enabled the code to run for me (O365).
Disabling screen updating will help prevent screen flashes and improve performance.
Because lines are of unequal length you also need to collapse the selection before moving it down a line otherwise some lines will get skipped.
Sub AddNonBreakingSpace()
Application.ScreenUpdating = False
'store current view type so it can be restored later
Dim viewType As WdViewType
viewType = ActiveWindow.View.Type
'change to Draft view to prevent crashing
ActiveWindow.View.Type = wdNormalView
Dim myRange As Range
Set myRange = ActiveDocument.Range(ActiveDocument.Range.Start, ActiveDocument.Range.Start)
myRange.Select
Selection.Expand wdLine
While Selection.End < ActiveDocument.Range.End
If Right(Selection.Text, 1) = " " And IsNumeric(Left(Selection.Words.Last, 1)) = True Then
Selection.Characters.Last = Chr(160)
End If
'collapse selection to avoid missing any lines
Selection.Collapse wdCollapseStart
Selection.MoveDown wdLine, 1
Selection.Expand wdLine
Wend
'restore original view
ActiveWindow.View.Type = viewType
Application.ScreenUpdating = True
End Sub
I've made a macro to change the header color of a document, but when hitting the end of the document - or if there's no remaining header - I'm getting an error.
What I want is after the last header, at the end of the document, to exit my Do Loop.
Here's my code:
Sub Changecolortest5()
'
' Changecolortest5 Macro
'
'
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
Do
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
Selection.Font.Color = 8527984
ActiveWindow.ActivePane.View.NextHeaderFooter
Loop
'Exit Header and Footer
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
Addressing Headers/Footers optimally doesn't work well with recorded macros, so I'm going to show you a slightly different approach than what you give us. The code below works directly with the underlying objects and applies formatting to the Range rather than a selection. This is faster and the screen doesn't "flicker".
When working with a group of things, such as Headers, it's more usual to use a For-Each loop to cycle through the group. In this case, Headers are specific to Sections, so you loop the Sections. Something along these lines:
Dim doc as Word.Document
Dim sec as Word.Section
Set doc = ActiveDocument
For Each sec in doc.Sections
sec.Headers(wdHeaderFooterPrimary).Range.Paragraphs(1).Range.Font.Color = 8527984
sec.Headers(wdHeaderFooterFirstPage).Range.Paragraphs(1).Range.Font.Color = 8527984
Next
In addition, if you look up the Help topic for Do loops you'll see that they require a test to end the loop: Do While or Do Until or Loop While or Loop Until a certain criterium is met. I'm pretty sure the code you show us must be giving you an error - when asking questions you should always include all relevant information, including any error messages...
I am currently setting up some MS Word templates in Word 2010 and have encountered a problem, where text suddenly disappears at the end of a paragraph.
The problem only occurs in some specific scenarios, but I have experienced that it can be recreated in a lot of different ways. I have not, however, been able to pinpoint the exact reason why this happens. Therefore, I would like to find the specific reason, that makes the issue occur, in order to avoid it.
It seems that a combination of the existence of wrapped tables, content in the page header and a certain length of a line can invoke the issue.
To recreate a document where this issue occurs, please follow this procedure:
Open a new document in Word 2010.
Copy the code below into a new module in the VBA editor.
Run the A_ReplicateScenario macro to insert example content in the document.
Place the cursor at the end of line 3 (the line that ends close to the margin).
Type a new sentence after the dot, beginning with a space.
The text that you have typed, will disappear when the margin is reached.
The text will then be shown if for instance a character is deleted from the original text (i.e. from the beginning of the line) or if a formatting change is made (e.g. clear formatting). The 'Show all' setting in Word can also sometimes display the text, but will only display it while 'Show all' is activated. Other times Word will display 'ghosted' double lines which can not be selected.
A short video of the replicated issue can be viewed here: https://youtu.be/Bqp9STDRkXc
Sub A_ReplicateScenario()
Call SetUpNormalStyle
Call InsertBodyTextLines
Call InsertHeaderTextLines
Call InsertWrappedTables
Call SetUpMargins
Call InsertExampleBodyText
End Sub
Sub SetUpNormalStyle()
With ActiveDocument.Styles("Normal").Font
.Name = "Arial"
.Size = 10
End With
With ActiveDocument.Styles("Normal").ParagraphFormat
.SpaceAfter = 0
.LineSpacingRule = wdLineSpaceAtLeast
.LineSpacing = 12
End With
End Sub
Sub InsertBodyTextLines()
For i = 1 To 4
Selection.TypeParagraph
Next
End Sub
Sub InsertHeaderTextLines()
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
For i = 1 To 26
Selection.TypeParagraph
Next
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
Sub InsertWrappedTables()
Selection.HomeKey Unit:=wdStory
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
With Selection.Tables(1).Rows
.WrapAroundText = True
.HorizontalPosition = CentimetersToPoints(2)
.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
.VerticalPosition = CentimetersToPoints(4.5)
.RelativeVerticalPosition = wdRelativeVerticalPositionPage
End With
Selection.Tables(1).Columns(1).PreferredWidthType = wdPreferredWidthPoints
Selection.Tables(1).Columns(1).PreferredWidth = CentimetersToPoints(11)
Selection.MoveDown Unit:=wdLine, Count:=1
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
With Selection.Tables(1).Rows
.WrapAroundText = True
.HorizontalPosition = CentimetersToPoints(10)
.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
.VerticalPosition = CentimetersToPoints(8)
.RelativeVerticalPosition = wdRelativeVerticalPositionPage
End With
Selection.Tables(1).Columns(1).PreferredWidthType = wdPreferredWidthPoints
Selection.Tables(1).Columns(1).PreferredWidth = CentimetersToPoints(9)
End Sub
Sub SetUpMargins()
With ActiveDocument.PageSetup
.TopMargin = CentimetersToPoints(3.8)
.BottomMargin = CentimetersToPoints(2.8)
.LeftMargin = CentimetersToPoints(2.3)
.RightMargin = CentimetersToPoints(1.5)
End With
End Sub
Sub InsertExampleBodyText()
With Selection
.HomeKey Unit:=wdStory
.MoveDown Unit:=wdLine, Count:=3
.TypeText Text:="Ouwouwouwoiwoiuwoiuwoiuwoiuwoiuwoiuwoiw oiwu oiwu owiu woiu woiuw oiwu owiu owiu ww."
.TypeParagraph
.TypeText Text:="Woiuwoiuwoiuw."
End With
End Sub
The problem is related to the tables being formatted to float around the text. Word has a long history of issues with floating objects. And although Word has improved a lot over the years you might still experience problems, in particular with floating tables.
If you change the formatting of the second table (via Table Properties) and set the text wrapping to None, the bug goes away (YMMV).
My recommendation would be to avoid the floating tables if possible.
I have a Word macro that finds the selected text throughout the document, highlights all occurrences, and returns to the starting point (via a bookmark it sets first). The only problem is, after running it, Word displays the page above the bookmark (where the cursor is). The cursor isn't on screen at all.
After running it, I can tap a key and the screen moves to display the entry point. I added a line to do the same thing within the macro (move right one character), and it still drops me a page above. I tried using SmallScroll on the window, but that moves the insertion point. I need to end up where I started.
What can I do?
Sorry about not posting the code before, I couldn't get it to format as code. (I blame IE8 on a federal network.)
Sub AcronymHilighter()
''''''''''''''''''''''''''''''''''''''''
' Check that user has selected some text
''''''''''''''''''''''''''''''''''''''''
Dim strGetAcronym As String
If Not Selection.Type = wdSelectionNormal Then
MsgBox "Please select some text.", vbInformation
Exit Sub
End If
'''''''''''''''''''
' Set a bookmark at the current location
'''''''''''''''''''
ActiveDocument.Bookmarks.Add _
Name:="MarkReturn", Range:=Selection.Range
'''''''''''''''''''
' Save the current track changes state, then turn it off
'''''''''''''''''''
Dim bTrackingAsWas As Boolean
bTrackingAsWas = ActiveDocument.TrackRevisions
ActiveDocument.TrackRevisions = False
ActiveDocument.ShowRevisions = False
''''''''''''''''''
' Find & highlight the text
''''''''''''''''''
strGetAcronym = Selection.Text
Selection.Range.HighlightColorIndex = wdYellow
Selection.Collapse wdCollapseEnd
With Selection.Find
.Text = strGetAcronym
.Highlight = False
.Wrap = wdFindContinue
.MatchCase = True
Do While .Execute
Selection.Range.HighlightColorIndex = wdYellow
Loop
End With
'''''''''''''''''''''''''''''
' Return to the starting point,
' restore Track Changes to the previous state
'''''''''''''''''''''''''''''
Selection.GoTo what:=wdGoToBookmark, Name:="MarkReturn"
ActiveWindow.SmallScroll Down:=2
ActiveDocument.TrackRevisions = bTrackingAsWas
ActiveDocument.ShowRevisions = True
End Sub
Pardon my excessive commenting, I like to remind myself what everything does; the last time I wrote code, it was in BASIC in 1985.
I'm not fully aware of your problem (since you didn't post your code), but this bit does the work you described:
Sub MarkAndGoBack()
With ActiveDocument.Bookmarks
.Add Range:=Selection.Range, Name:="Bookmark"
.DefaultSorting = wdSortByName
.ShowHidden = False
End With
Dim doc As Document
Dim para As Paragraph
Set doc = ActiveDocument
For Each aWord In doc.Words
If aWord.Text = "WantedWord" Then aWord.HighlightColorIndex = wdYellow
Next aWord
Selection.GoTo What:=wdGoToBookmark, Name:="Bookmark"
ActiveDocument.Bookmarks("Bookmark").Delete
With ActiveDocument.Bookmarks
.DefaultSorting = wdSortByName
.ShowHidden = False
End With
End Sub
It searches for the Word "WantedWord" and highlights it yellow. After that, you will be forwarded to your initially created bookmark. It shows the correct page with cursor for me. If you want to do an Input search, you have to replace "WantedWord" with an InputBox.
I want to insert text with custom formatting, then change the font style back to what it was before the code was run.
Dim myText As String
Dim oldFont As Object
'Save old font
Set oldFont = Selection.Font
'Insert text with custom font
myText = "CUSTOM STRING"
Selection.Font.Name = "Comic Sans MS"
Selection.Font.Size = 26
Selection.Font.Bold = True
Selection.TypeText (myText)
'Revert font back to original
Set Selection.Font = oldFont
Can anyone explain a way to do what I'm looking for?
Edit: I should have been more specific. If I am typing text, I have a certain formatting that I am typing in that is shown on the Home Tab (eg. Comic Sans Ms, Size 22, Bold). When I insert text with the code, this changes the formatting that I am typing with, so if I continue typing it will be in the NEW font type, not the Comic Sans MS. I am trying to make it so if I continue typing after I have inserted the text via VBA code, it will retain my old formatting.
One simple solution is to store all properties that you are going to change, and to reset them at the end:
Dim myText As String
Dim oldFont As String
Dim oldSize As Integer
Dim oldBold As Boolean
'Save old font
oldFont = Selection.Font.Name
oldSize = Selection.Font.Size
oldBold = Selection.Font.Bold
'Insert text with custom font
myText = "CUSTOM STRING"
Selection.Font.Name = "Comic Sans MS"
Selection.Font.Size = 26
Selection.Font.Bold = True
Selection.TypeText (myText)
'Revert font back to original
Selection.Font.Name = oldFont
Selection.Font.Bold = oldBold
Selection.Font.Size = oldSize
The trick I find helpful when writing Word macros is simply to replicate what I'd be doing if I was using the Word GUI. When I want to paste formatted text but keep my current format, I type a space, paste in the text before the space then delete the space. As the space has my original format that's how I get it back.
So, doing this as a macro:
'Type a space
Selection.TypeText Text:=" "
'Move Cursor back one character
Selection.MoveLeft Unit:=wdCharacter, Count:=1
'Insert text with custom font
myText = "CUSTOM STRING"
Selection.Font.Name = "Comic Sans MS"
Selection.Font.Size = 26
Selection.Font.Bold = True
Selection.TypeText (myText)
'Move Cursor forward one character
Selection.MoveRight Unit:=wdCharacter, Count:=1
'Delete the space
Selection.TypeBackspace
This will preserve any properties of the text you originally had.
I can't quite figure out exactly what you're trying to do there, but Selection.TypeText will collapse the selection down to the insertion point, so you effectively have no characters selected by the time you try to "revert the font". You either need to re-select the text, or use a Range object instead of the Selection to identify the text to be affected.
The reason that you get an error at the line:
Set Selection.Font = oldFont
...is because - unusually, and perversely - you should not use the Set keyword when assigning to the Font property. Rather than storing a reference to a Font object, the assignment simply applies the properties of the assigned font.
This is very confusing API design, made all the more confusing because you do need to use the Set keyword when reading the Font property, and because that does assign a reference to a Font object!
And that's the other reason why your code won't work - you're taking a reference to a Font object which you then modify, and your reference points to the same Font object that has now changed.
What you actually need to do is create a new Font object to store the original font details, as follows:
Set oldFont = Selection.Font.Duplicate
The Selection.Font object is read only.
This means that there is no way to restore all the settings in one assignment. Since you are only changing a few properties the easiest solution is to save each individual value and restore them afterwards as stephan suggests.
I.e. Save properties:
oldFontName = Selection.Font.Name
oldFontSize = Selection.Font.Size
oldFontBold = Selection.Font.Bold
Do you stuff and then restore properties:
Selection.Font.Name = oldFontName
Selection.Font.Size = oldFontSize
Selection.Font.Bold = oldFontBold
See, if this piece of code gives you enough hint.
CopyFormat picks up the existing formatting by moving left from current cursor.
PasteFormat applies it to a character & from there on, the original formatting (which was copied) comes into effect.
Selection.MoveLeft unit:=wdWord, Count:=1
Selection.EndKey Extend:=wdExtend
Selection.CopyFormat
Selection.MoveRight unit:=wdWord
'* New text and new formatting
Selection.Font.Bold = True
Selection.Font.Italic = True
Selection.Font.Size = 28
Selection.TypeText "hello world"
Selection.TypeText " "
Selection.MoveLeft unit:=wdCharacter, Count:=1
Selection.EndKey Extend:=wdExtend
Selection.PasteFormat
Selection.TypeText "original formatting here"
Sub No_Format()
'
' No_Format Macro
'
'
Selection.PasteSpecial Link:=False, DataType:=wdPasteText
End Sub
this will allow you to paste the text and adopting the new formatting.