Insert text with center align - vba

im using this method to add text but it aligned at left.
how to make it center of document?
With ActiveDocument.Content
.InsertAfter "hello world!"
End With

The new para is the last one of the document >> use .paragraphs.last
Sub test()
With ActiveDocument.Content
.InsertParagraphAfter 'to be safe that new content is on its own para = last para of document
.InsertAfter "hello world!"
.Paragraphs.Last.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
End With
End Sub
``

Related

Replacing Paragraph causes it to go into Infinite loop

I need to proccess text by paragraphs. Next example shows taking a paragraph and removing its last character - the paragraph character. Then I proccess this text and try to replace old text with a new one. The problem is that it goes into infinite loop and freezes Word.
Sub Parser()
For Each para In ActiveDocument.Paragraphs
If Len(para.Range.Text) >= 150 Then
CleanedString = Left(para.Range.Text, Len(para.Range.Text) - 1)
'Some proccessing here
para.Range.Text = CleanedString & vbCr
End If
Next
End Sub
I also tried removing all the paragraphs and placing them back after processing, but it also failed.
Its an infinite loop because you are adding a new paragraph to the end of your text. Consequently every time you process a string the document gets 1 paragraph longer. The trick is to adjust the range before you process the text.
Sub Parser()
For Each para In ActiveDocument.Paragraphs
para.range.moveend unit:=wdcharacter, count =-1
If Len(para.Range.Text) >= 150 Then
CleanedString = para.Range.Text
'Some proccessing here
para.Range.Text = CleanedString
End If
Next
End Sub
Right solution was near, thanks #freeflow. I acutally needed to wrap it into With
For Each para In ActiveDocument.Paragraphs
If Len(para.Range.Text) >= 150 Then
With para.Range
.MoveEnd Unit:=wdCharacter, Count:=-1
NewText = .Text
.Text = NewText
End With
End If
Next

Word VBA Loop through bookmarks of similar names

I have a userform that allows users to insert an intentionally blank page after the cover page if they need to print the document. I can get this to work just fine when i only need to insert 1 or 2 blank pages throughout the document, however I now have a new document where i need to insert a total of 14 blank pages if the userform combobox is changed to "Printable Format"
The code i use for the current document is below as reference but I think for adding so many blank pages i'm better to use a loop or find instead of this.
All of my bookmarks for where blank pages are to be added are named "Print" with sequential numbers (ie. "Print 1", Print2" etc) so i was hoping to be able to search through the document for all bookmarks containing the name "Print" but i can't seem to figure it out!
Dim answer As Integer
Dim BMBreak As Range
Dim BMBreak2 As Range
With ActiveDocument
'Insert bookmarks applicable to Printable Format
If CbxPrint.Value = "Printable Format" Then
answer = MsgBox("You have changed the document to Printable Format." & vbNewLine _
& "This will add intentionally blank pages throughout the document " & vbNewLine _
& "Do you wish to continue?", vbOKCancel, "WARNING")
If answer = vbOK Then
'Intentional blank page after title page
Set BMRange = ActiveDocument.Bookmarks("Print1").Range
BMRange.Collapse wdCollapseStart
BMRange.InsertBreak wdPageBreak
BMRange.Text = "THIS PAGE IS INTENTIONALLY BLANK"
BMRange.ParagraphFormat.SpaceBefore = 36
BMRange.ParagraphFormat.Alignment = wdAlignParagraphCenter
ActiveDocument.Bookmarks.Add "Print1", BMRange
With BMRange
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdSectionBreakContinuous
End With
With ActiveDocument.Sections(3)
.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
End With
With ActiveDocument.Sections(2)
.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
.Headers(wdHeaderFooterPrimary).Range.Delete
.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
.Footers(wdHeaderFooterPrimary).Range.Delete
End With ```
Code like the following will process any number of Print# bookmarks (presently limited to 20, which need not all exist):
Dim i As Long, BMRange As Range
With ActiveDocument
If CbxPrint.Value = "Printable Format" Then
If MsgBox("You have changed the document to Printable Format." & vbCr & _
"This will add intentionally blank pages throughout the document " & vbCr _
& "Do you wish to continue?", vbOKCancel, "WARNING") = vbOK Then
'Process bookmarks applicable to Printable Format
For i = 20 To 1 Step -1
If .Bookmarks.Exists("Print" & i) = True Then
'Intentional blank page
Set BMRange = .Bookmarks("Print" & i).Range
With BMRange
.Collapse wdCollapseEnd
.InsertBreak Type:=wdSectionBreakNextPage
.InsertBreak Type:=wdSectionBreakNextPage
.Start = .Start - 1
.Sections.Last.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
.Sections.Last.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
With .Sections.First
.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
.Headers(wdHeaderFooterPrimary).Range.Delete
.Footers(wdHeaderFooterPrimary).Range.Delete
.Range.InsertBefore "THIS PAGE IS INTENTIONALLY BLANK"
.Range.ParagraphFormat.SpaceBefore = 36
.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
End With
.Start = .Start - 1
.Bookmarks.Add "Print" & i, .Duplicate
End With
End If
Next
End If
End If
End With

Cannot change style in Word using VBA

I have a paragraph like this:
Nov 19, 2014 - You are running the search on the Selection, but you're
not changing that selection between runs. So you just end up making
the same text bold over and over again. Here's a way to do what you're
doing without the Selection object: Sub ParaStyle() Dim objPara As
Paragraph For Each objPara In ... Word VBA Paragraph
formatting-VBForums
And I am trying to change the style of the entire paragraph to a local style. I am using the following code:
Dim rgePages As Range
Dim p As Paragraph
Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=3
Set rgePages = Selection.Range
Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=6
rgePages.End = Selection.Bookmarks("\Page").Range.End
rgePages.Select
For Each p In rgePages.Paragraphs
If p.Style <> "Heading 1" Then
p.Style = "Body Text"
'p.Style = Word.WdBuiltinStyle.wdStyleBodyText
rgePages.Collapse Word.WdCollapseDirection.wdCollapseEnd
End If
Next
It is working fine till the time any line or a few words are in different style. Say for example if the line
So you just end up making
in the paragraph is in different style, it is marking the whole paragraph as "Body Text" except for that part. Is there a solution to this?
You could try to clear formatting first before you apply your own style. It could go this way:
....
If p.Style <> "Heading 1" Then
p.Range.Select
Selection.ClearFormatting 'it rather works with selection only
p.Style = "Body Text"
....

Moving words within a text

I am trying to create two keyboard shortcuts which allow me to move selected words quickly to the right and left within a text. The selected text should move one word to the left or the right.
Here is what I want to do
1) Select words e.g. “this is” in the sentence “this is a tree”
2) Press e.g. ctrl + alt + arrow to the right
3) The sentence reads now as “a this is tree”
4) Press again ctrl alt + arrow to the right
5) The sentence reads now as “a tree this is”
The idea is to replace the cut / paste steps and make the process a bit more efficient and smoother.
I have no knowledge in VB, but managed to get close to by using Word’s macro-function.
Sub moveRight()
'moveRight Macro
Selection.Cut
Selection.moveRight Unit:=wdWord, Count:=1
Selection.PasteAndFormat (wdFormatOriginalFormatting)
End Sub
The problem with this function is that the selected words are no longer selected once they are pasted. Hence, triggering the function again (=moving the text more than one word) results in an error (I would have to select the relevant text again). Is there any way that the selected words remain selected after they are pasted so that I can trigger the function repeatedly?
Many thanks.
You might like to try this solution. The first two procedures below should be called by your keyboard shortcuts. The both call the same executing sub, but with different parameters.
Sub MoveSelectionLeft()
' call with keyboard shortcut
GetSelection True
End Sub
Sub MoveSelectionRight()
' call with keyboard shortcut
GetSelection False
End Sub
Private Sub GetSelection(ByVal ToLeft As Boolean)
' 22 Apr 2017
Dim Rng As Range
Dim SelTxt As String ' selected text (trimmed)
Dim Sp() As String
Set Rng = Selection.Range
With Rng
SelTxt = Trim(.Text)
If ToLeft Then
.MoveStart wdWord, -1
Else
.MoveEnd wdWord, 1
End If
Sp = Split(Trim(.Text))
If ToLeft Then
.Text = SelTxt & " " & Sp(0) & " "
Else
.Text = Sp(UBound(Sp)) & " " & SelTxt & " "
End If
.Find.Execute SelTxt
.Select
End With
End Sub
A cheap way of doing this is with bookmarks. At some point before and after moving the text, run AddBookMark and DeleteBookMark respectively.
Public Sub AddBookMark()
Dim myDocument As Document
Set myDocument = ActiveDocument
myDocument.Bookmarks.Add "MySelectedText", Selection
End Sub
Public Sub DeleteBookMark()
Dim myDocument As Document
Set myDocument = ActiveDocument
myDocument.Bookmarks("MySelectedText").Delete
End Sub
Sub moveRight()
Dim myDocument As Document
Set myDocument = ActiveDocument
Selection.Cut
Selection.moveRight Unit:=wdWord, Count:=1
Selection.PasteAndFormat (wdFormatOriginalFormatting)
myDocument.Bookmarks("MySelectedText").Select
End Sub

let MS-Word vba ActiveDocument.Paragraphs(2).Select select paragraph 1 only?

I want to add many hyperlinks via VBA for my MS-Word file, for 1st paragraph the hyperlink is "./index/1.doc", 2nd paragraph is "./index/2.doc", and so on. The simpilfied procedure is 1)select one paragraph 2)add hyperlink, just as the following code says. However, the VBA code gives every paragraph same hyperlink which only should be for the last paragraph. So, is there any way to deselect in VBA to perform this case? Thanks
btw, the VBA can be tested on any MS-Word file with more than 1 paragraphs.
Sub addHypertext()
For countParagraph = 1 To ActiveDocument.Paragraphs.Count
Selection.Collapse Direction:=wdCollapseEnd
set para = ActiveDocument.Paragraphs(countParagraph)
para.Select
Set paraStyle = para.Style
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, \
Address:="./index/" & countParagraph & ".doc"
Rem this does not work
Rem Selection.Range.Style = paraStyle
Rem this does not work
Selection.Style = paraStyle
Rem this does not work too
Rem para.Style = paraStyle
Rem this produces "run-time error"
Rem para.Range.Style = "text"
Next
End Sub
I see what's happening. It is highlighting the paragraph tag and making it part of the hyperlink. I am curious if maybe you might just want to add a reference at the end of each paragraph instead. See if this is something you might want to try:
Sub addHypertext()
Dim para As Paragraph
For countParagraph = 1 To ActiveDocument.Paragraphs.Count
Selection.Collapse Direction:=wdCollapseEnd
Set para = ActiveDocument.Paragraphs(countParagraph)
para.Range.Select
Selection.MoveRight 1
Selection.MoveLeft 1
Selection.Font.Superscript = True
Selection.TypeText "[" + Trim(Str(countParagraph)) + "]"
Selection.MoveLeft Count:=Len("[" + Trim(Str(countParagraph)) + "]"), Extend:=wdExtend
para.Range.Hyperlinks.Add Anchor:=Selection.Range, _
Address:="./index/" & countParagraph & ".doc"
Selection.Font.Superscript = False
Next
End Sub
The above will put a reference link at the end of each paragraph like wikipedia does on their site.
The following will get the whole paragraph as the link as it looks like you initially wanted:
Sub addHypertext()
Dim para As Paragraph
For countParagraph = 1 To ActiveDocument.Paragraphs.Count
Selection.Collapse Direction:=wdCollapseEnd
Set para = ActiveDocument.Paragraphs(countParagraph)
para.Range.Select
Selection.MoveEnd Count:=-1
para.Range.Hyperlinks.Add Anchor:=Selection.Range, _
Address:="./index/" & countParagraph & ".doc"
Next
End Sub
EDIT
To answer your addition as to styles, the following still keeps the link and changes the style.
Sub addHypertext()
Dim para As Paragraph
For countParagraph = 1 To ActiveDocument.Paragraphs.Count
Selection.Collapse Direction:=wdCollapseEnd
Set para = ActiveDocument.Paragraphs(countParagraph)
para.Range.Select
Selection.MoveEnd Count:=-1
para.Range.Hyperlinks.Add Anchor:=Selection.Range, _
Address:="./index/" & countParagraph & ".doc"
para.Range.Select
Selection.MoveEnd Count:=-1
'Per your comments below for future visitors
Selection.Style = "Normal"
Selection.Style = "My Custom Style"
Next
End Sub