我想以自定义格式插入文本,然后将字体样式改回运行代码之前的样式。

Dim myText As String
Dim oldFont As Object
'Save old font
Set oldFont = Selection.Font

'Insert text with custom font
myText = "CUSTOM STRING"
Selection.Font.Name = "Comic Sans MS"
Selection.Font.Size = 26
Selection.Font.Bold = True
Selection.TypeText (myText)

'Revert font back to original
Set Selection.Font = oldFont


谁能解释一种方法来做我想要的?

编辑:我应该更具体。如果我输入文字,则输入的格式一定会显示在“首页”标签上(例如,Comic Sans Ms,22号字体,粗体)。当我在代码中插入文本时,这会更改我键入时使用的格式,因此,如果我继续键入,它将使用新的字体类型,而不是Comic Sans MS。我正在尝试这样做,因此,如果我在通过VBA代码插入文本后继续输入文字,它将保留原来的格式。

最佳答案

一种简单的解决方案是存储要更改的所有属性,并在最后重置它们:

Dim myText As String
Dim oldFont As String
Dim oldSize As Integer
Dim oldBold As Boolean

'Save old font
oldFont = Selection.Font.Name
oldSize = Selection.Font.Size
oldBold = Selection.Font.Bold

'Insert text with custom font
myText = "CUSTOM STRING"
Selection.Font.Name = "Comic Sans MS"
Selection.Font.Size = 26
Selection.Font.Bold = True
Selection.TypeText (myText)

'Revert font back to original
Selection.Font.Name = oldFont
Selection.Font.Bold = oldBold
Selection.Font.Size = oldSize

07-28 13:52