生成一段在word中使用的vba程序,实现以下功能:一级标题设置三号字体,二级标题设置四号字体,正文设置五号字体,正文段首缩进两个字符,并自动计算每段正文的字数,将计算的字数添加到每段的段首并用小括号括起来
时间: 2023-03-05 19:57:19 浏览: 162
以下是生成在Word中使用的VBA程序,实现所述功能的代码:
```
Sub SetFontAndIndentation()
'设置一级标题字体
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = "^p"
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute
While Selection.Find.Found
Selection.Style = ActiveDocument.Styles("标题 1")
Selection.Font.Size = 14
Selection.Find.Execute
Wend
'设置二级标题字体
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = "^p"
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute
While Selection.Find.Found
Selection.Style = ActiveDocument.Styles("标题 2")
Selection.Font.Size = 12
Selection.Find.Execute
Wend
'设置正文字体和段首缩进
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = "^p"
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute
While Selection.Find.Found
Selection.Style = ActiveDocument.Styles("正文")
Selection.Font.Size = 10
Selection.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0.74)
Selection.Find.Execute
Wend
'添加每段正文的字数
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = "^p"
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute
While Selection.Find.Found
'获取段落的文本
Dim paraText As String
paraText = Selection.Range.Text
'计算段落的字数
Dim paraLen As Integer
paraLen = Len(paraText) - 1
'在段首添加字数和小括号
Selection.HomeKey Unit:=wdLine
Selection.TypeText Text:="(" & paraLen & ")"
Selection.MoveRight Unit:=wdCharacter, Count:=2
Selection.Find.Execute
Wend
End Sub
```
注释已经在代码中说明了每一步的操作。如果需要使用这个程序,只需将代码复制到Word中的VBA编辑器中,并在需要应用样式和段首缩进的文档中运行该程序即可。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)