MS Word: Getting the actual ASCII code of an inserted symbol - vba

I am trying to write a VBA code for MS-Word to remove rows with the unticked symbol from a table.
To do that, I need MS-Word to recognize it and differentiate between it and the ticked symbol. But unlike Excel, MS-Word seems to be bad at it.
To focus on the problem, I inserted the symbols, but I can not get the correct ASCII code of the character I have just inserted.
Here is what I tried:
Sub SymbolsTest()
Selection.InsertSymbol 163, "Wingdings 2", True 'Insert unticked
Selection.MoveRight Unit:=wdCharacter, Count:=-1, Extend:=wdExtend 'Select it
Debug.Print AscW(Selection.Text) & " " & Selection.Text 'Ask for ASCII
Selection.Collapse 0
Selection.InsertSymbol 82, "Wingdings 2", True 'Insert ticked
Selection.MoveRight Unit:=wdCharacter, Count:=-1, Extend:=wdExtend 'Select it
Debug.Print AscW(Selection.Text) & " " & Selection.Text 'Ask for ASCII
End Sub
The output is:
40 (
40 (
I would expect it to be:
163 ?
82 ?
I also tried ?Selection.Characters(1) = Selection.Characters(2) in the immediate window while selecting both of them, and I got True
Any help would be appreciated.

As far as I know
there is no simple way to get the character's code point or font name directly using any of the properties of the Selection or Range
In this situation, Word always uses the code point 40 (")"), and internally, it does does store the name of the font you specified and a Unicode codepoint (e.g. U+F052 for the checked box).
Two things you can do. If the character is not 40, assume it already has the correct codepoint (although I am not certain about that). But if not,
retrieve the .XML or .WordOpenXML of the Selection or Range and look for the relevant element, e.g. ><w:sym w:font="Wingdings 2" w:char="F052"/> in both the old-style .XMLand the newer .WordOpenXML. You could either search for the text <w:sym and look for the font and codepoint in the following text, or "do it properly" using an XML parser. In that case, it may be useful to know that F052 either means "the Unicode character with code point F052, or it means "it's F000 + the code point in the original character set", i.e. Wingdings 2 in this case.
e.g. one way would be to make a reference in the VB Editor's Tools-References to the Microsoft XML library (in this case 6.0) and use code along these lines:
Sub getCharFontAndCodepoint()
Dim xdoc As MSXML2.DOMDocument60
Dim xSymNodes As MSXML2.IXMLDOMNodeList
Set xdoc = New MSXML2.DOMDocument60
xdoc.async = False
If xdoc.LoadXML(Selection.XML) Then
xdoc.SetProperty _
"SelectionNamespaces", _
"xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml'"
Set xSymNodes = xdoc.SelectNodes("//w:sym/#w:font")
If xSymNodes.Length > 0 Then
Debug.Print xSymNodes(0).NodeValue
End If
Set xSymNodes = xdoc.SelectNodes("//w:sym/#w:char")
If xSymNodes.Length > 0 Then
Debug.Print xSymNodes(0).NodeValue
End If
End If
Set xSymNodes = Nothing
Set xdoc = Nothing
End Sub
or, if you only need the codepoint, copy the character and use paste special to paste it using the Unformatted Unicode Text format, e.g.
Selection.Copy
Selection.PasteSpecial link:=False, DataType:=22 ' There does not seem to be a named enum for this particular format
Selection.MoveLeft Unit:=WdUnits.wdCharacter, Count:=1, Extend:=WdMovementType.wdExtend
Debug.Print Hex(AscW(Selection))
Selection.Document.Undo

Related

Add images and captions programmatically, with bold label

I would like to add captions to figures where chapters would be included in the numbering, and the text "Figure x.x." was bold:
Figure 1.1. Sample figure.
Autocaptions is not possible because it will only allow for styles named Heading 1-9 to be considered as chapters, while I am using a custom style. As I understand, there is no way to include any personalised style to the list.
Please take into consideration that my knowledge of VBA is virtually nonexistant (I usually try to find a similar problem in multiple forums and adapt it using guides or other similar solved problems), so my error might be trivial for those who are more experienced. I could manage to write a macro to do almost everything I needed, but there is this one thing that is not working as expected.
Ideally, the macro would:
Prompt the user to select an image
Insert the image with a specific paragraph style
Insert a caption that includes chapter number with a custom paragraph style, instead of builtin ones
Search for "Figure x.x." text and make it bold using Find and Replace with wildcards <== This is where I'm having problems
Sub PicCaption()
Dim intChoice As Integer
Dim strPath As String
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
End If
'insert the image
Selection.InlineShapes.AddPicture FileName:= _
strPath, LinkToFile:=False, _
SaveWithDocument:=True
Selection.Range.Style = "Figures"
'Add caption in the form of "Figure x.x. "
Selection.TypeParagraph
Selection.TypeText Text:="Figure "
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"STYLEREF ChapNum \n \t", PreserveFormatting:=False
Selection.TypeText Text:="."
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"SEQ Figure \* ARABIC", PreserveFormatting:=False
Selection.TypeText Text:="."
Selection.Style = ActiveDocument.Styles("Figures")
Selection.TypeText Text:=" "
'Make "Figure x.x." bold (last space not included)
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Forward = False
.Text = "Figure*.*"
.Font.Bold = False
.MatchWildcards = True
.Replacement.Text = "^&"
.Replacement.Font.Bold = True
.Execute Replace:=wdReplaceOne, Forward:=True, _
Wrap:=wdFindContinue
End With
End Sub
The replacing bit does not make the recently inserted "Figure x.x." bold, but the next one in the text, even if I specified the search to be backwards. If I type .Execute Replace:=wdReplaceOne, Forward:=False, _, it goes to the end of the document and moves upwards, making everything bold.
In my sample document I have multiple already captioned images, but that wouldn't normally be the case; I would like to format captions as I insert them, instead of reformatting them when the document is finished.
Where is my mistake and why, if you were so kind to explain?
Thank you kindly.
I found my answer: for whatever reason, once fields are involved, finding and replacing does not work that well; i.e. it won't correctly find periods within "1.1.". I tried it with and without wildcards, using ?, * and anything I could think of.
I resorted to another method:
Select whole line
Make bold
Go to the end of the line
Uncheck bold so that the description has normal font width
'Code before this point remains identical
'Make "Figure x.x." bold (last space not included)
'Select from cursor point to beginning of line; make bold
Selection.MoveStart Unit:=wdLine, Count:=-1
Selection.Font.Bold = True
'Move cursor to end of the line; uncheck bold format
Selection.EndKey Unit:=wdLine
Selection.Font.Bold = wdToggle
This way, the cursor is placed right after the caption label, bold not selected. Seems clumsy and highly unprofessional, but works.
Thanks, everyone!
When Word inserts a caption it is basically providing a shortcut for the insertion of a number of fields and their associated switches.
Thus if we insert a Figure caption that references Heading 3 style for the chapter numbers we get something like
Figure 2.1.3-1: Text for the caption
If we highlight the 'Figure 2.1.3-1' in the Word document and press Shift-F9 this will show that the caption numbering is composed of a styleref field and a seq field
Figure {Styleref 3 \w}-{Seq Figure}
When the field codes are shown we can easily use the built in Find/Replace of word to change the text between the field brackets. So we could search for 'Styleref 3' and replace it with 'Styleref "Heading 2"' or in fact 'Styleref "myStyle"'.
If the Word wildcard search is used then you can simultaneously change the style ref to the desired style and apply the bold effect, thus achieving the effect that the OP desires. I'll leave that to a little research by the OP.
This is fine if we have to convert an existing document. If we are inserting Captions as we type then it would be preferable to use a macro to insert the caption numbering that is desired by firing a macro that inserts the appropriate caption numbering/formatting from a set of keystrokes.
The macro below will insert a caption of the type desired, use the defined style for chapter numbering and apply the bold effect to all the numbering upto the separating tab.
Option Explicit
' Any Leading and Trailing spaces in the Const definition strings are deliberate
' Heading 2 is used for ease of demonstration. Heading 2 should be replaced by the style
' from which you wish to take the heading numbers.
Const SpecialCaptionStyle As String = """Heading 2""" ' Name of the style to reference for the heading number
Const CaptionType As String = "Figure " ' The trailing space is required
Const CaptionNUmberingStyle As String = " \w " ' see switches for the styleref field
Const CaptionNumberSeparator As String = "-"
Public Sub InsertSpecialCaption()
' Get the range into which we insert the styleref and seq fields
Dim myFieldRange As Word.Range
Set myFieldRange = Selection.Range
'Preserve the srarting range for later use
Dim myEffectRange As Word.Range
Set myEffectRange = Selection.Range.Duplicate
'Set the style to Caption style.
'Caption style will be applied to any text in the paragraph of the selection point
myFieldRange.Collapse direction:=wdCollapseEnd
myFieldRange.Paragraphs.Item(1).Style = myFieldRange.Document.Styles(wdStyleCaption)
'Insert the label of the caption type. In this case it is the text 'Figure'
myFieldRange.InsertAfter Text:=CaptionType
myFieldRange.Collapse direction:=wdCollapseEnd
Dim myField As Word.Field
' Insert the styleref field to obtain the heading number of the style we specify
Set myField = myFieldRange.Document.Fields.Add(Range:=myFieldRange, Preserveformatting:=False)
myField.Code.Text = "Styleref " & SpecialCaptionStyle & CaptionNUmberingStyle
Set myFieldRange = myField.Result
'Insert the text string used as a seperator between the chapter number and the captiontype number
myFieldRange.InsertAfter Text:=CaptionNumberSeparator
myFieldRange.Collapse direction:=wdCollapseEnd
' Insert the Seq field to get the sequential number of the caption
' in this case we use the same name of the label but it could be different
Set myField = myFieldRange.Document.Fields.Add(Range:=myFieldRange, Type:=wdFieldEmpty, Preserveformatting:=False)
myField.Code.Text = "Seq " & CaptionType
Set myFieldRange = myField.Result
myFieldRange.Collapse direction:=wdCollapseEnd
' Insert the seperator text from the number to the Caption text NB I always use : followed by a tab
myFieldRange.InsertAfter Text:=":" & vbTab
' Adjust the range to omit the tab from formatting
' update the fields
' Apply bold effect to the inserted caption label
myFieldRange.MoveEnd unit:=wdCharacter, Count:=-1
myEffectRange.End = myFieldRange.End
myEffectRange.Fields.Update
myEffectRange.Font.Bold = True
End Sub
All that is required is to link the macro to a suitable key sequence, which is the provenance of the OP.
First though, I'd strongly suggest using F8 to step through the macro to see how the Caption number is inserted.

Making links to Places in this document work in vba

I'm trying to make a VBA script that will take all the headings in a document and make a table of contents out of them, with hyperlinks to each of the headings. The headings are all found, parsed and all the hyperlinks are made, however they don't correctly reach their destination which is a place within the document. The default 'create hyperlink to Place in this document' code looks like this:
Selection.Range.Hyperlinks(1).Range.Fields(1).Result.Select
Selection.Range.Hyperlinks(1).Delete
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
SubAddress:="_Test_Heading"
Selection.Collapse Direction:=wdCollapseEnd
This is the code that you would get if you recorded a macro while using the 'Edit hyperlink' window.
Edit hyperlink window
The address field where normally there would be a URL is empty, while the subaddress field is filled by the name of the header with underscores.
I think the problem is that Word defaults to 'Existing file or web page' rather than 'Place in this document', even if 'Place in this document' were specified prior. If I switch the mode of a link to 'Place in this document' without changing the subaddress or anything else, it works - but having to go and do that for each link defeats the purpose of the script. I've been looking all over for a way to express 'Place in this document' in VBA but haven't found anything. Tried bookmarks as an alternative and that didn't work either. Any help would be appreciated.
I found a workaround using cross-referencing. In case it helps anyone in the future:
Private Function GetLevel(strItem As String) As Integer
Dim strTemp As String
Dim strOriginal As String
Dim longDiff As Integer
strOriginal = RTrim$(strItem)
strTemp = LTrim$(strOriginal)
longDiff = Len(strOriginal) - Len(strTemp)
GetLevel = (longDiff / 2) + 1
End Function
Sub TableofContents()
Dim i As Integer
Dim AllHeadings As Variant
AllHeadings = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading)
Selection.HomeKey Unit:=wdStory
Selection.HomeKey Unit:=wdLine
For i = LBound(AllHeadings) To UBound(AllHeadings)
strtext = Trim$(AllHeadings(i))
Level = GetLevel(CStr(AllHeadings(i)))
If Level = 2 Then
Selection.InsertCrossReference ReferenceType:="Heading", ReferenceKind:= _
wdContentText, ReferenceItem:=i, InsertAsHyperlink:=True, _
IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" "
Selection.TypeParagraph
End If
Next
End sub
The first function gets the level of the heading.
The second part moves to the top of the document and starts inserting cross-references to the headings that I want (in this case I want it to be = 2).

Finding and Replacing with VBA for Word overwrites previous style

I'm writing a VBA script to generate word documents from an already defined template. In it, I need to be able to write headings along with a body for each heading. As a small example, I have a word document that contains only <PLACEHOLDER>. For each heading and body I need to write, I use the find-and-replace feature in VBA to find <PLACEHOLDER> and replace it with the heading name, a newline, and then <PLACEHOLDER> again. This is repeated until each heading name and body is written and then the final <PLACEHOLDER> is replaced with a newline.
The text replacing works fine, but the style I specify gets overwritten by the next call to the replacement. This results in everything I just replaced having the style of whatever my last call to my replacement function is.
VBA code (run main)
Option Explicit
Sub replace_stuff(search_string As String, replace_string As String, style As Integer)
With ActiveDocument.Range.Find
.Text = search_string
.Replacement.Text = replace_string
.Replacement.style = style
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchWholeWord = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Sub
Sub main()
Dim section_names(2) As String
section_names(0) = "Introduction"
section_names(1) = "Background"
section_names(2) = "Conclusion"
Dim section_bodies(2) As String
section_bodies(0) = "This is the body text for the introduction! Fetched from some file."
section_bodies(1) = "And Background... I have no issue fetching data from the files."
section_bodies(2) = "And for the conclusion... But I want the styles to 'stick'!"
Dim i As Integer
For i = 0 To 2
' Writes each section name as wsStyleHeading2, and then the section body as wdStyleNormal
Call replace_stuff("<PLACEHOLDER>", section_names(i) & Chr(11) & "<PLACEHOLDER>", wdStyleHeading2)
Call replace_stuff("<PLACEHOLDER>", section_bodies(i) & Chr(11) & "<PLACEHOLDER>", wdStyleNormal)
Next i
Call replace_stuff("<PLACEHOLDER>", Chr(11), wdStyleNormal)
End Sub
Input document: A word document with only <PLACEHOLDER> in it.
<PLACEHOLDER>
Expected Output:
I expect that each heading will be displayed in the style I specified and can be viewed from the navigation pane like this:
Actual Output: However what I actually get is everything as wdStyleNormal style like this:
I think the problem can be solved by inserting a paragraph break between every style transition, but when I try using vbCrLF or Chr(10) & Chr(13) or vbNewLine instead of the chr(11) I am using now, Each line begins with a boxed question mark like this:
Update from discussion in comments on another answer. The problem described below applies to Word 2016 and earlier. Starting in Office 365 (and probably Word 2019, but that's not been confirmed) the Replace behavior has been changed to "convert" ANSI 13 to a "real" paragraph mark, so the problem in the question would not occur.
Answer
The reason for the odd formatting behavior is the use of Chr(11), which inserts a new line (Shift + Enter) instead of a new paragraph. So a paragraph style applied to any part of this text formats the entire text with the same style.
In this particular case (working with Replace), vbCr or the equivalent Chr(13) also don't work because these are not really Word's native paragraph. A paragraph is much more than just ANSI code 13 - it contains paragraph formatting information. So, while the code is running, Word is not really recognizing these as true paragraph marks and the paragraph style assignment is being applied to "everything".
What does work is to use the string ^p, which in Word's Find/Replace is the "alias" for a complete paragraph mark. So, for example:
replace_stuff "<PLACEHOLDER>", section_names(i) & "^p" & "<PLACEHOLDER>", wdStyleHeading2
replace_stuff "<PLACEHOLDER>", section_bodies(i) & "^p" & "<PLACEHOLDER>", wdStyleNormal
There is, however, a more efficient way to build a document than inserting a placeholder for each new item and using Find/Replace to replace the placeholder with the document content. The more conventional approach is to work with a Range object (think of it like an invisible selection)...
Assign content to the Range, format it, collapse (like pressing right-arrow for a selection) and repeat. Here's an example that returns the same result as the (corrected) code in the question:
Sub main()
Dim rng As Range
Set rng = ActiveDocument.content
Dim section_names(2) As String
section_names(0) = "Introduction"
section_names(1) = "Background"
section_names(2) = "Conclusion"
Dim section_bodies(2) As String
section_bodies(0) = "This is the body text for the introduction! Fetched from some file."
section_bodies(1) = "And Background... I have no issue fetching data from the files."
section_bodies(2) = "And for the conclusion... But I want the styles to 'stick'!"
Dim i As Integer
For i = 0 To 2
BuildParagraph section_names(i), wdStyleHeading2, rng
BuildParagraph section_bodies(i), wdStyleNormal, rng
Next i
End Sub
Sub BuildParagraph(para_text As String, para_style As Long, rng As Range)
rng.Text = para_text
rng.style = para_style
rng.InsertParagraphAfter
rng.Collapse wdCollapseEnd
End Sub
The problem is caused by your use of Chr(11) which is a manual line break. This results in all of the text being in a single paragraph. When the paragraph style is applied it applies to the entire paragraph.
Replace Chr(11) with vbCr to ensure that each piece of text is in a separate paragraph.

Check if a Range of text fits onto a single line

I'm programmatically filling in a regulated form template where lines are predefined (as table cells):
(Using plain text Content Controls as placeholders but this isn't relevant to the current question.)
So, I have to break long text into lines manually (auto-adding rows or something is not an option because page breaks are also predefined).
Now, since characters have different width, I cannot just set some hardcoded character limit to break at (or rather, I can, and that's what I'm doing now, but this has proven to be inefficient and unreliable, as expected). So:
How do I check if a Range of text fits on a single line -- and if it doesn't, how much of it fits?
I've checked out Range Members (Word) but can't see anything relevant.
The only way is to .Select that text, them manipulate the selection. Selection in the only object for which you can use wdLine as a boundary. Nothing else in the Word object model works with automatic line breaks.
Sub GetFirstLineOfRange(RangeToCheck As Range, FirstLineRange As Range)
'Otherwise, Word doesn't always insert automatic line breaks
'and all the text will programmatically look like it's on a single line
If Not Application.Visible Or Not Application.ScreenUpdating Then
Application.ScreenRefresh
End If
Dim SelectionRange As Range
Set SelectionRange = Selection.Range
Set FirstLineRange = RangeToCheck
FirstLineRange.Select
Selection.Collapse Direction:=wdCollapseStart
Selection.EndOf Unit:=wdLine, Extend:=wdExtend
Set FirstLineRange = Selection.Range
If FirstLineRange.End > RangeToCheck.End Then
FirstLineRange.End = RangeToCheck.End
End If
SelectionRange.Select
End Sub
Function IsRangeOnOneLine(RangeToCheck As Range) As Boolean
Dim FirstLineRange As Range
GetFirstLineOfRange RangeToCheck, FirstLineRange
IsRangeOnOneLine = FirstLineRange.End >= RangeToCheck.End
End Function
The subroutine GetFirstLineOfRange takes a RangeToCheck and sets FirstLineRange to the first text line in the given range.
The function IsRangeOnOneLine takes a RangeToCheck and returns True if the range fits on one line of text, and False otherwise. The function works by getting the first text line in the given range and checking whether it contains the range or not.
The manipulation of the Selection in GetFirstLineOfRange is necessary because the subroutine wants to move the end of the range to the end of the line, and the movement unit wdLine is available only with Selection. The subroutine saves and restores the current Selection; if this is not necessary then the temporary variable SelectionRange and the associated statements can be deleted.
Note:
There is no need to scroll anything - which in any event is not reliable. Try something based on:
With Selection
If .Characters.First.Information(wdVerticalPositionRelativeToPage) = _
.Characters.Last.Information(wdVerticalPositionRelativeToPage) Then
MsgBox .Text & vbCr & vbCr & "Spans one line or less."
Else
MsgBox .Text & vbCr & vbCr & "Spans more than one line."
End If
End With

Generate bookmarks in Word 2010 programmatically, with the header name as the bookmark name

I need to generate bookmarks in Word 2010 programmatically, with the header name as the bookmark name.
I have the following code which makes a word a bookmark, but the bookmark name remains the same as the string Heading 1 is only available in the name variable:
Sub bookmarking()
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
With ActiveDocument.Bookmarks
.Add Range:=Selection.Range, Name:=" Heading 1"
.DefaultSorting = wdSortByName
.ShowHidden = False
End With
End Sub
Instead of the Heading 1 in the name variable, I want content from the clipboard. Please help me replace that Heading 1 with clipboard content.
Use a DataObject from the Microsoft Forms 2.0 Object Library:
Private Function GetClipboardData()
Dim objDataObject As MSForms.DataObject ''need to add reference in Tools |References
Set objDataObject = New MSForms.DataObject
objDataObject.GetFromClipboard
On Error Resume Next
GetClipboardData = objDataObject.GetText
If Err.Number = -2147221404 Then
MsgBox "Error: current clipboard data is either empty or is not text. Clibpoard must contain text."
End If
End Function
Then, back your main code, have the bookmark name be this clipboard data:
...
.Add Range:=Selection.Range, Name:=GetClipboardData()
...
Is this a good start for you? There are other ways which may be more robust depending on your needs. However this should serve as good proof-of-concept.