Multiple objectsFont
Multiple objects
Contains font attributes (font name, font size, color, and so on) for an object.
Using the Font Object
Use the Font property to return the Font object. The following instruction applies bold formatting to the selection.
Selection.Font.Bold = True
The following example formats the first paragraph in the active document as 24point Arial and italic.
Set myRange = ActiveDocument.Paragraphs(1).Range
With myRange.Font
.Bold = True
.Name = "Arial"
.Size = 24
End With
The following example changes the formatting of the Heading 2 style in the active document to Arial and bold.
With ActiveDocument.Styles(wdStyleHeading2).Font
.Name = "Arial"
.Italic = True
End With
Remarks
You can use the New keyword to create a new, stand-alone Font object. The following example creates a Font object, sets some formatting properties, and then applies the Font object to the first paragraph in the active document.
Set myFont = New Font
myFont.Bold = True
myFont.Name = "Arial"
ActiveDocument.Paragraphs(1).Range.Font = myFont
You can also duplicate a Font object by using the Duplicate
property. The following example creates a new character style with the character formatting from the selection as well as italic formatting. The formatting of the selection isn’t changed.
Set aFont = Selection.Font.Duplicate
aFont.Italic = True
ActiveDocument.Styles.Add(Name:="Italics", _
Type:=wdStyleTypeCharacter).Font = aFont
VBA is a Microsoft script language, mostly used with Excel. And there are reasons for this – mainly, the skills needed to use VBA are easily grasp by those, using Excel on a daily basis. The second reason is that only in Excel the VB Editor gives a possibility to record a macro. Thus, if you want to use VBA in Access, Word, Outlook or any other MS Application, you should know the commands from before and you need some skills, as far as you cannot just record the macro and simply edit it later.
That is why I have decided to give some useful examples for VBA with Word. This is really not popular, because Word is used mainly for writing 🙂 and not for creating business models, but some of the examples may be useful.
The first example of VBA will simply change the font of the Word document to “Times New Roman”. In order to make it fancier, we will ask a question before the change:
The code is pretty much straightforward, we get a message box, the result of the message box is assigned to a variable “intResult”, and if this result is “6”, we change the font. In VBA, “6” is the value, generated from the “Yes” button:
So, the code looks like this:
Sub ChangeFont() Dim intResult As Integer Dim strMessage As String Dim myRange As Range strMessage = «Do you want to change the font with ««Times New Roman»«?» intResult = MsgBox(strMessage, vbYesNo + vbDefaultButton2, «Change Font») If intResult = vbYes Then Set myRange = ActiveDocument.Paragraphs(1).Range myRange.WholeStory myRange.Font.Name = «Times New Roman» End If End Sub |
Pretty much, the code may seem a little useless, because the same result can be achieved if you simply select the whole text in Word and change the font. No VBA, nothing. Anyway, this is a good code for reference, if you need to select all text in Word (and Word does not have macro recorder).
In the second example, we will add automatically some text at the beginning and the end of the document. The text added will be hard coded, for easier understanding of the example. Pretty much, the logic is as in the previous example, we simply ask with a message box and if the answer is VbYes, we add some text at the beginning and at the end:
Sub ChangeBeginningAndEnd() Dim intResult As Integer Dim strMessage As String Dim rng As Word.Range strMessage = «Should we add something to the beginning and the end of the document?» intResult = MsgBox(strMessage, vbYesNo + vbDefaultButton2, _ «Change Starting and Ending») If intResult = vbYes Then Set rng = ActiveDocument.Range(Start:=0, End:=0) rng.Text = «VitoshAcademy.com» & vbCr Set rng = ActiveDocument.Range rng.EndOf wdStory, wdMove rng.Text = «www.facebook.com/vitoshacademy» & vbCr & «www.youtube.com/user/vitoshacademy» End If End Sub |
Finally, the last example is something useful – it changes all font with some size to another size. Thus, imagine that you are writing a master thesis of 60 pages, and suddenly you decided to change the size of font from 9 to 10. You cannot go and select all, because there are other fonts. Thus, you need to use a macro! 🙂 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
Sub ChangeFontSize() Dim intResult As Integer Dim strMessage As String strMessage = «Do you want to change all Fonts with size 9 to size 10?» intResult = MsgBox(strMessage, vbYesNo + vbDefaultButton2, «Change Fonts») If intResult = vbYes Then Selection.HomeKey unit:=wdStory With Selection.Find .ClearFormatting .Font.Size = 9 .Text = «» .Forward = True .Wrap = wdFindContinue .Format = True .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False Do Until .Execute = False With Selection .Font.Size = 10 .Collapse End With Loop End With End If End Sub |
The macro here makes a search in the text for font with size 9 and sets it to size 10. The trick is in the usage of a loop in a “With… End With” structure. The trick of the finding is in the clearing of the format.
Pretty much, that is all. If you want to test the macros, you may download the files from here.
I want to create a word document using Excel VBA, and add text with various font styles and sizes. Here is my code:
Sub CreateNewWordDoc()
Dim wrdDoc As Word.Document
Dim wrdApp As Word.Application
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Add
Dim charStart As Long
Dim charEnd As Long
With wrdDoc
For i = 1 To 3
charStart = wrdApp.Selection.Start
.Content.InsertAfter (" some text")
charEnd = wrdApp.Selection.End
If i = 1 Then
'set the text range (charStart,charEnd) to e.g. Arial, 8pt
Else
If i = 2 Then
'set the text range (charStart,charEnd) to e.g. Calibri, 10pt
Else
'set the text range (charStart,charEnd) to e.g. Verdana, 12pt
End If
End If
Next i
.Content.InsertParagraphAfter
.SaveAs ("testword.docx")
.Close ' close the document
End With
wrdApp.Quit
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
How can I define font style and size on-the-fly in the if-else statement above?
asked Feb 23, 2014 at 21:46
Would something like this fit the bill?
Sub CreateNewWordDoc()
Dim doc As Word.Document
Dim toAdd As String
Dim lengthAdded As Long
Dim selStart As Long
Set doc = ActiveDocument
toAdd = "Hello World" ' What to add?
lengthAdded = Len(toAdd) ' For later!
selStart = Selection.Start ' Where to add the text?
doc.Range(selStart).InsertAfter (toAdd)
With doc.Range(selStart, selStart + lengthAdded)
' Here's where the font stuff happens
.Font.Name = "Arial"
.Font.Size = 15
End With
End Sub
Note that I’ve got rid of most of the code which isn’t directly pertinent to the question. Hopefully you can extrapolate from my code to yours!
answered Feb 24, 2014 at 0:20
LondonRobLondonRob
70.6k36 gold badges142 silver badges197 bronze badges
1
In this article, I will discuss on how to detect the font size and change the font size to the size as we want to change with two examples of code. In the first example, it is about changing the font size within the defined range of font size and in the second one; it is about changing all font size to one defined size.
To work with the font size with vba, we need to use Word.Range to detect the font size and change the font size. Here are the two example of codes
Example 1: Changing font size withthe defined font size
SubStandardizeFontSize (oWord As Word.Range)
IfoWord.Font.Size < 16 And oWord.Font.Size > 12 Then
oWord.Font.Size = 16
ElseIfoWord.Font.Size < 12 And oWord.Font.Size > 11 Then
oWord.Font.Size = 12
ElseIfoWord.Font.Size <= 11 And oWord.Font.Size > 9 Then
oWord.Font.Size = 11
ElseIfoWord.Font.Size <= 9 Then
oWord.Font.Size = 10
ElseIfoWord.Font.Size = 9999999 Then‘999999 — represents word with characters of different size
sFontSize = oWord.Characters(1).Font.Size
Forj = 1 To oWord.Characters.Count
IfoWord.Characters(j).Font.Size = sFontSize Then: oWord.Characters(j).Font.Size = 12
Else: oWord.Characters(j).Font.Size = 10
End If
Next
End If
EndSub
Example 2: Change font size to a 12 pt
PublicSub ChangeFontSize()
DimoParagraph As Paragraph
DimoRange As Range
Dimi, j As Integer
DimsFontSize As Single
ForEach oParagraph In Selection.Paragraphs
Set oRange = oParagraph.Range
Fori = 1 To oRange.Words.Count
IfoRange.Words(i).Font.Size = 9999999 Then‘999999 — represents word with characters of different size
sFontSize = oRange.Words(i).Characters(1).Font.Size
Forj = 1 To oRange.Words(i).Characters.Count
IfoRange.Words(i).Characters(j).Font.Size = sFontSize Then
oRange.Words(i).Characters(j).Font.Size = 12
Else
oRange.Words(i).Characters(j).Font.Size = 12
End If
Next
End If
Next
Next
EndSub
How to test this Code
1. Open Ms Word
2. Open VB Editor or Alt+F11
3. Create new module
4. Copy and paste the Code
5. Go back to you word and go to Macro Dialog then select the Macro Name StandardizeFontSize and Click on Run
1 2 3 4 5 6 7 8 9 10 11 12 |
Function Translit(ByVal sValue As String) As String 'Переменные Dim sRussian As String, iCount As Integer, sTranslit As Variant 'Запись с русскими буквами sRussian = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" 'Массив с англ. буквами sTranslit = Array("", "A", "B", "V", "G", "D", "E", "Yo", "Zh", "Z", "I", "J", "K", "L", "M", "N", "O", "P", "R", "S", "T", "U", "F", "Kh", "C", "Ch", "Sh", "Shh", "``", "Y", "`", "E'", "Yu", "Ya", "a", "b", "v", "g", "d", "e", "yo", "zh", "z", "i", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "kh", "c", "ch", "sh", "shh", "``", "y", "`", "e'", "yu", "ya") For iCount = 1 To 66 'Начало цикла sValue = Replace(sValue, Mid(sRussian, iCount, 1), sTranslit(iCount), , , vbBinaryCompare) Next 'Конец цикла Translit = sValue 'Присвоение значения End Function |
- Remove From My Forums
-
Question
-
Hello,
Basically all I want to do is change the default font by clicking on a button. Then when another document is opened that font is used. Below is my code which sets the font of the «normal style», then copies that style to the normal.dot. This works for my home computer but I need to be able to this another way.
Is there a quicker or another way to achieve this without having to hard code in the location of the normal.dot
Many Thanks
Private Sub CommandButton1_Click()
With ActiveDocument.Styles(wdStyleNormal).Font
.Name = «Wingdings 2»
.Size = 12
End With
‘ For Each styleloop In ActiveDocument.Styles
‘ If styleloop = «Normal» ThenApplication.OrganizerCopy Source:=ActiveDocument.Name, _
Destination:=»C:Documents and SettingsAlex WilliamsApplication DataMicrosoftTemplatesNormal.dot», _
Name:=»Normal», _
Object:=wdOrganizerObjectStyles
‘ End If
‘Next styleloop
End Sub