Setting the font in MS Word VBA

S

Steve Marotta

This shouldn't be this hard, but I can't seem to find any easy answers.

I have a Range variable, and all I want to do is set the font for that
Range, so that when I do an InsertAfter() on that Range, it will insert
with a given font. I've tried doing myRange.Font.Name as well as
myRangeFont.NameAscii and neither works.
If anyone has any ideas, please let me know. Thanks!

~ Steve
 
G

Greg Maxey

Maybe something like:

Sub Scratchmacro()
Dim myRange As Range
Set myRange = Selection.Range
With myRange
.InsertAfter ("blah, blah")
.Font.Name = "Arial"
End With
End Sub
 
S

Steve Marotta

Thanks, that worked!

Weird. It seems counterintuitive that the command to set the font
should be *after* the Insert command. Why is that?

~ Steve
 
G

Greg Maxey

Steve,

If found that if you have something selected before running the macro then
it doesn't matter if the .font.name line is before or after the the
insertafter line. It must have something to do with there not really being
an object to apply the font name attribute to until after the text is
inserted. I am just taking baby steps with VBA, perhaps one of the experts
will be along to offer a better explanation.
 
H

Helmut Weber

Hi Greg, hi Steve,

I do not consider myself to be an expert, though I am trying hard.
What makes using ranges difficult sometimes, is that they change
without warning, plus this mystery:

Dim myRange As Range
Selection.Collapse ' just in case
Set myRange = Selection.Range
MsgBox Len(myRange.Text) ' = 0 !!!
MsgBox Len(Selection.Text) ' = 1 !!! it never becomes 0
MsgBox Len(Selection.Range.Text) ' = 0 !!!

Inserting after the range is a paradox in a way,
as the range grows with inserting.

With myRange
.Font.Name = "Times New Roman" ' range is of length 0
.InsertAfter ("blah, blah") ' range is growing, but it's too late
End With

With myRange
.InsertAfter ("blah, blah") ' range is growing
.Font.Name = "Times New Roman" ' range has grown
End With

Greetings from Bavaria, Germany
Helmut Weber, MVP
"red.sys" & chr(64) & "t-online.de"
Word XP, Win 98
http://word.mvps.org/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top