Text with different styles in one paragraph Word VBA - vba

I want to have bold and not bold text in one line.
With objWrdDoc
.Styles.Add ("S2")
.Styles.Add ("S3")
.Styles("S2").Font.Bold = True
.Styles("S3").Font.Bold = False
End With
With objWrdApp.Selection
.TypeParagraph
.Style = objWrdDoc.Styles("S2")
.TypeText Text:="I want to have bold "
.Style = objWrdDoc.Styles("S3")
.TypeText Text:="and not bold text in one line."
End With
As a result, the entire text is not bold.

While working with the Selection object feels "intuitive", it's not as accurate for writing code to manipulate Word as using Range objects. You can think about a Range as being an invisible selection, with the important differences that
code can work with multiple Range objects
the user can't affect where a Range is (clicking on the screen or pressing arrow keys changes a Selection)
tracking where a Range is at any given point in the code is reliable
Changing the code in the question to work with a "target" Range could look as follows.
(Note that I've also added Style objects for the styles being defined. It's much more reliable and a lot less typing to work with objects, rather than constructs such as objWrdDoc.Styles("S3").)
Dim S2 as Word.Style, S3 as Word.Style 'As Object if using late-binding
With objWrdDoc
Set S2 = .Styles.Add("S2")
Set S3 = .Styles.Add("S3")
S2.Font.Bold = True
S3.Font.Bold = False
End With
Dim objRange as Word.Range 'As Object if using late-binding
Set objRange = objWrdApp.Selection.Range
With objRange
.Text = vbCr 'Chr(13) = paragraph mark
'The new text should follow the inserted paragraph mark
'Like pressing right-arrow to "collapse" a selection
.Collapse wdCollapseEnd
'When working with ranges, apply the formatting after writing the text
.Text = "I want to have bold "
.Style = S2
.Collapse wdCollapseEnd
.Text = "and not bold text in one line."
.Style = S3
End With

Related

How to print row of found string?

I'd like to find several strings within Word document and for each string found, I like to print (debug.print for example) the whole row content where the string is found, not the paragraph.
How can I do this? Thanks
Sub FindStrings
Dim StringsArr (1 to 3)
StringsArr = Array("string1","string2","string3")
For i=1 to 3
With
Selection.Find
.ClearFormatting
.Text = Strings(i)
Debug.Print CurrentRow 'here I need help
End With
Next
End Sub
The term Row in Word is used only in the context of a table. I assume the term you mean is Line, as in a line of text.
The Word object model has no concept of "line" (or "page") due to the dynamic layout algorithm: anything the user does, even changing the printer, could change where a line or a page breaks over. Since these things are dynamic, there's no object.
The only context where "line" can be used is in connection with a Selection. For example, it's possible to extend a Selection to the start and/or end of a line. Incorporating this into the code in the question it would look something like:
Sub FindStrings()
Dim StringsArr As Variant
Dim bFound As Boolean
Dim rng As Word.Range
Set rng = ActiveDocument.content
StringsArr = Array("string1", "string2", "string3")
For i = LBound(StringsArr) To UBound(StringsArr)
With rng.Find
.ClearFormatting
.Text = StringsArr(i)
.Wrap = wdFindStop
bFound = .Execute
'extend the selection to the start and end of the current line
Do While bFound
rng.Select
Selection.MoveStart wdLine, -1
Selection.MoveEnd wdLine, 1
Debug.Print Selection.Text
rng.Collapse wdCollapseEnd
bFound = .Execute
Loop
End With
Set rng = ActiveDocument.content
Next
End Sub
Notes
Since it's easier to control when having to loop numerous times, a Range object is used as the basic search object, rather than Selection. The found Range is only selected for the purpose of getting the entire line as these "Move" methods for lines only work on a Selection.
Before the loop can continue, the Range (or, if we were working with a selection, the selection) needs to be "collapsed" so that the code does not search and find the same instance of the search term, again. (This is also the reason for Wrap = wdFindStop).

How to search from a certain point in a document down and end the search?

I have the following code that searches for a certain point in a document and creates a search range until the end of the document. Then within that range it removes the paragraph following entirely bold paragraphs (subheadings), ignoring any styles that aren't Normal and aren't in a table. However, it seems to search the entire document (i.e. the beginning as well). How can I make it only search the range (i.e. from where I've positioned the cursor down to the end of the document)?
Dim aPara As Paragraph
Dim oSearchRange As Range
With Selection.Find
.Text = "Dear "
End With
Selection.MoveDown Unit:=wdParagraph, Count:=4
Set oSearchRange = Selection.Range
oSearchRange.End = ActiveDocument.Content.End
oSearchRange.MoveEnd wdParagraph, -1
For Each aPara In oSearchRange.Paragraphs
If aPara.Range.Font.Bold = True And aPara.Range.Next.Style = ActiveDocument.Styles("Normal") And Not aPara.Range.Next.Information(wdWithInTable) Then aPara.Range.Next.Delete
Next aPara
Thanks
I needed to add .Execute after the "Dear " search, thanks to Teamothy (:

How to replace UTF8-character with clickable Checkbox in Word with Macros?

I have several Word-Files containing old-style non-clickable UTF8-character checkboxes () and I want to replace them with real, clickable Checkboxes. They should be unchecked for  and checked for another specified UTF8-character (which I do not know the number of right now).
I tried search and replace and copying from macros I've found online. I'm not a word user and this is a one-time-task, so I sadly do not have the time to learn VBA well enough to write such a thing as a macro.
I've found this online, but in the Macros-Window, I cannot even copy  to "string to be searched".
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "string to be searched"
.Replacement.Text = "string to be replaced"
.Wrap = wdFindContinue
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = False
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
For Searching UTF=8 Character you have to search Unicodes like
U+2610 decimal &#9744 Unchecked Checkbox
U+2611 decimal &#9745 Checked Checkbox
U+2612 decimal &#9746 Crossed Checkbox
Other like Unicode characters may also be explored for exactly what is it in your case. I tested with U+2610 decimal &#9744 Unchecked Checkbox.
For replacement with FormField type of ComboBox I successfully used the code below
Sub TestFormFieldCB()
Dim Rng As Range, cb As FormField
ActiveDocument.Content.Select
With Selection.Find
.Text = ChrW(9744)
Do While .Execute
Set Rng = Selection.Range
ht = Rng.Font.SizeBi
Rng.Delete
Set cb = Rng.FormFields.Add(Rng, wdFieldFormCheckBox)
cb.CheckBox.Size = ht
Loop
End With
'ActiveDocument.Protect wdAllowOnlyFormFields
End Sub
The disadvantage of this type ComboBox is document is to be protected for the ComboBox to be clickable.
As Second option I tried with ActiveX Type ComboBox. It is easilyclickable even in unprotected mode but difficult to align and size with the text in the line. Also Somehow i could not use the same find Loop as in the above code and had to work around with some other way.
The final tested code is
Sub testActiveXCB()
Dim Rng As Range, cb As InlineShape, Fnd As Boolean
ActiveDocument.Content.Select
With Selection.Find
.Text = ChrW(9744)
.Execute
Do While Selection.Find.Found
Set Rng = Selection.Range
ht = Rng.Font.SizeBi
Rng.Delete
Set cb = Rng.InlineShapes.AddOLEControl(ClassType:="Forms.CheckBox.1")
Debug.Print cb.OLEFormat.Object.Name & "-" & cb.Height
cb.Width = cb.Height
cb.Width = ht
cb.OLEFormat.Object.Caption = ""
cb.OLEFormat.Object.PicturePosition = 2
'Use next Line when replacing Checked Unicode Char mat be U+2611 or U+2612
'cb.OLEFormat.Object.Value = True
ActiveDocument.Content.Select
Selection.Find.Execute
Loop
End With
End Sub
(All tests are carried out in Word 2007 only)
I request more answers and eager to learn from Word VBA experts regarding
Why the ActiveX Combo Box could not be inserted with the simple Find loop used in case of FormField type Combo Box?
How to effectively align Active X Combo Box with the text Line?

Index has incorrect page numbers

I'm building an index via a macro, and after a little bit, the page numbers start to get wonky. At first, they are correct, but as we go deeper in the document, they start getting offset.
I have a hunch it's because the code I'm using uses a range (.Index.MarkEntry Range:=theRange ...), and the page of the end of the range is where the page number comes from.
How can I make sure that the page number the index uses, is the page that has the first character in the range (does that make sense? Whatever page the entry starts on, is the page I want to use).
Here's my (truncated for relevance) code:
Sub Find_Definitions()
Dim myDoc As Word.Document
Dim oRng As Word.Range, rng As Word.Range, rngXE As Word.Range, tempHold As Word.Range
Dim addDefinition$, findText$, editedDefinition$
Dim meanTypes() As Variant
Dim rngEdited
Dim y&
Dim bFound As Boolean
meanTypes = Array(Chr(150) & " means", Chr(151) & " means", "- means", Chr(150) & " meaning", Chr(151) & " meaning", "- meaning")
Set myDoc = ActiveDocument
bFound = True
Call Clear_Index
For y = LBound(meanTypes) To UBound(meanTypes)
'Loop through the document
Set oRng = myDoc.Content
Set rngXE = oRng.Duplicate
With oRng.Find
.ClearFormatting
.ClearAllFuzzyOptions
'.Text = findText
.Text = meanTypes(y)
.MatchCase = False
.Wrap = wdFindStop
End With 'orng.find
Do While bFound
bFound = oRng.Find.Execute
If bFound Then
Set rngXE = oRng.Paragraphs(1).Range.Duplicate
rngXE.Select
' Here's where I could check the text, and see if it starts with Roman numerals.
editedDefinition = Check_For_Roman_Numerals(rngXE, findText)
If editedDefinition <> "" Then 'If editedDefinition is empty, that means there's no definition to add to the index
Set rngEdited = rngXE.Duplicate
With rngEdited
.moveStart unit:=wdCharacter, Count:=x
.Select
‘ This next line is my idea that the range’s page number is being used, so I just wanted to print it to see.
Debug.Print rngEdited.Information(wdActiveEndPageNumber)
End With 'rngEdited
myDoc.Indexes.MarkEntry Range:=rngEdited, entry:=editedDefinition, entryautotext:=editedDefinition
End If ''editedDefinition <> ""
oRng.Collapse wdCollapseEnd
oRng.Start = oRng.Paragraphs(1).Range.End
oRng.End = myDoc.Content.End
rngEdited.Collapse wdCollapseEnd
rngEdited.End = myDoc.Content.End
' Set rngXE = Nothing
End If 'bFound
Loop
bFound = True
Next y
TheEnd:
Set rng = Nothing
myDoc.Indexes(1).Update
MsgBox ("Added all definitions.")
End Sub
I'm thinking what I'll need to do is to "tighten up" the editedRange, so it ends on the same page? But if a definition spans a page break, I want to use the smaller of the page numbers that it appears on (the first one).
Thanks for any ideas/tips/thoughts.
Generally, when the page numbers in an Index don't match with what you expect it's because the document is displaying content that won't be in the printed result. This affects the pagination on-screen, "pushing" content "down" in the document. Most often, the reason is field codes, which can be suppressed by pressing Alt+F9 until the field results display.
This approach does not work for XE (index markers) and some other field types, as well as hidden text, however. They display whenever the display of "Hidden" text is allowed. Depending on the settings in File/Options/Display/"Always show these formatting marks on the screen" clicking the "backwards P" button in the Ribbon's Home tab may or may not turn them off. If it does not, then you have to go into options to togge the display, or create a macro to do this and run it as required.
The other possible reason is that the programmatically generated XE field was inserted at the end of a long range of text that broke to another page, instead of being on the page where the text starts. In order to ensure the field is the start, rather than the end of a Range, collapse the Range to its starting point:
rngEdited.Collapse wdCollapseStart

VBA insert picture and legends word 2010

A vba script that seems simple but don't work exactly as I want .
My script inserts images ( PNG files) in the current document with a caption after each picture that is the name of the file.
So to insert images I use:
Selection.InlineShapes.AddPicture FileName: = sFile
Selection.TypeParagraph
And to insert text after I use:
Set Opar = ActiveDocument.Paragraphs.Add
oPar.Range.Text = sFile
oPar.Range.Style = " Normal"
The problem is that images are all found in the beginning of the document , arranged in reverse order (the last image inserted appears first in the document) and legends are all found at the end of the document.
What's happening ?
#Boro: It's more efficient to work directly with the object model than trying to coerce Selection (imitating the user actions). There's no single way to achieve what you describe, so I'm going to demonstrate my preference:
Dim ils as Word.InlineShape
Dim rng as Word.Range
'Starting with current sel, but this could also be a Range...
Set ils = Selection.InlineShapes.AddPicture(FileName: = sFile)
Set rng = ils.Range
'Move the focus AFTER the picture
rng.Collapse wdCollapseEnd
'new para, text, followed by new para
rng.Text = vbCr & sFile & vbCr
rng.Style = wdStyleNormal
'focus in last para inserted by code
rng.Collapse wdCollapseEnd
'Do other things with the Range...
'Leave cursor there for user to work
rng.Select
The key in my approach is collapsing the Range, either to the start or end point. Think of it like pressing the left or right arrow key to reduce the selection to a blinking cursor. Except you can have any number of Ranges (but only one Selection) and things won't jump around on the screen.