Examining each character in a document

Any character in a document can be referenced directly. Consider a document that contains nothing more than the following text on lines 1 and 2:

Hello
?

This code will access individual letters within the document:

MsgBox ActiveDocument.Text.Item(0) ' returns 72

MsgBox ActiveDocument.Text.Item(1) ' returns 101

MsgBox ActiveDocument.Text.Item(2) ' returns 108

What's going on?

The Text object is actually returning a number code. So "H" = 72, "e" = 101 and "l" = 108. Anyone familiar with ASCII codes may recognize these numbers. Fortunately, you don't need to remember what the codes translate to - there's a built-in function to VBScript function, Chr(), that does this for you. For example:

MsgBox Chr(ActiveDocument.Text(0)) ' returns H

Note that the "Item" has been dropped - it's not necessary since Item is the default property of the Text object.

So let's examine the entire document:

For i = 0 to ActiveDocument.Text.Count - 1

MsgBox "Character number: " & i & ", code: " & ActiveDocument.Text(i) & ", text: " & Chr(ActiveDocument.Text(i)) 

Next

This will produce the output:

Character number: 0, code: 72, Text: H
Character number: 1, code: 101, Text: e
Character number: 2, code: 108, Text: l
Character number: 3, code: 108, Text: l
Character number: 4, code: 111, Text: o
Character number: 5, code: 13, Text:
Character number: 6, code: 63, Text: ?

Note there is no actual character to represent the Enter key (the output is blank).

A better way of coding the above is to make use of the With....End With VBScript statement so you don't have to keep writing ActiveDocument.Text repeatedly.

With ActiveDocument.Text

For i = 0 to .Count - 1 

x = .Item(i) 

MsgBox "Character number: " & i & ", code: " & x & ", text: " & Chr(x) 

Next 

End With