打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
VBA宏实现Word论文自动排版_vba word
userphoto

2023.10.02 重庆

关注

一、灵感与动机

        作为一名即将毕业的大四学生,不仅经历了设计、编写系统的痛苦,还经历了撰写论文的烦恼,尤其是最后论文排版阶段,非常的繁琐和费时。所以我就希望可以有一个自动排版的“脚本”,一开始认为可以通过Python完成(因为Python属实强大),但经过大量的搜索和学习,我发现Office中给用户提供了一个宏语言,用户可以自己通过编码完成除现有功能外的其他功能。其默认支持VB,此外还有JS和Python也可以进行下载并切换开发环境。

二、现状与开发过程

        在开发的过程中,也是遇到了很多很多困难。最重要的可能还是我还是太菜了ヽ(ー_ー)ノ,目前VBA宏的编写对Excel的操做更加实用和方便,所以网络资源中基本都是Excel的教程学习。导致关于Word中使用的VB操做的案例和教程微乎其微,只能自己通过摸索、阅读文档和让ChatGPT帮忙。给也想练习的小伙伴一些建议吧,少走弯路:

(1)一开始我参考的开发文档是VB的,如果你VB不好可以参考,地址:Visual Basic 文档 - 入门、教程、参考。 | Microsoft Learn

但如果是word中的VBA开发文档需要参考Microsoft提供的,地址:Visual Basic for Applications (VBA) 的 Word 对象模型 | Microsoft Learn

(2)AI不是全部,不能给你提供直接搬来就能用的代码,需要你辨识和改变,这才是AI在帮助你编码中最正确的用法。

三、总体效果

使用VB的窗体与宏功能建立联系,目前已实现的功能:

(1)目录样式

(2)1、2、3...级标题样式

(3)正文样式

(4)图注、表注样式

(5)表格样式

(6)页面设置样式

(7)摘要(中英)样式,包括关键词样式 

四、部分功能实现

(1)修改标题样式(1、2、3...级标题)

        以1级标题为例,首先找到类型为“标题 1”的样式段落,再修改其具体样式,如加粗、下划线、倾斜、行距、段前段后等。实现代码如下:

  1. Sub FormatHeading2() '修改1级标题
  2. Dim p As Paragraph
  3. For Each p In ActiveDocument.Paragraphs
  4. If p.Style = ActiveDocument.styles("标题 1") Then
  5. p.Range.Font.Bold = True
  6. p.Range.Font.Italic = True '设置倾斜
  7. p.Range.Font.Underline = wdUnderlineSingle '设置下划线(单下划线)
  8. p.Range.Font.Size = 15
  9. p.Range.Font.name = "宋体"
  10. p.Range.ParagraphFormat.Alignment = wdAlignParagraphRight
  11. p.Range.ParagraphFormat.spaceBefore = 20
  12. p.Range.ParagraphFormat.spaceAfter = 10
  13. p.Range.ParagraphFormat.LineSpacingRule = wdLineSpaceSingle '单倍行距
  14. p.Range.ParagraphFormat.CharacterUnitFirstLineIndent = 0
  15. p.Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0)
  16. End If
  17. Next p
  18. End Sub

其他更多详细的属性可自行查阅开发文档。

(2)修改目录内容样式

        对于目录中不同级别的标题的样式会存在差异,我查找并修改样式的过程是,先找到所有标题的名称,不同级别放入不同数组中,在每个数组遍历寻找第一次出现的段落修改其样式。注意注意:目录中的文本属于超链接文本!实现代码如下(以修改目录中1级标题为例):

  1. Sub updateDirectoryContentOneStyle() '注意超链接文本问题
  2. Dim p As Paragraph
  3. Dim one() As String
  4. Dim oneCount As Integer
  5. Dim i As Integer
  6. For Each p In ActiveDocument.Paragraphs
  7. If p.Style = ActiveDocument.styles("标题 1") Then
  8. ReDim Preserve one(oneCount) '扩展一级标题数组
  9. one(oneCount) = p.Range.text
  10. oneCount = oneCount + 1
  11. End If
  12. Next p
  13. '输出数组中保存的标题内容
  14. For i = 0 To UBound(one)
  15. Dim myRange As Range
  16. Dim myStyle As Style
  17. Set myRange = ActiveDocument.Content
  18. myRange.Find.Execute FindText:=one(i), Forward:=True '查找
  19. If myRange.Find.Found = True Then
  20. With myRange
  21. .Font.Bold = False
  22. .Font.name = "宋体"
  23. .Font.Size = 14
  24. End With
  25. End If
  26. Next
  27. End Sub

(3)查找特定文本并修改其样式

        本文以查找“关键词”三字为例。使用Find关键字进行查找,找到后修改其样式即可。更多的详细属性请参考开发文档,实现代码如下:

  1. Sub findText()
  2. Set myRange = ActiveDocument.Content
  3. myRange.Find.Execute FindText:="关键词", Forward:=True
  4. If myRange.Find.Found = True Then
  5. With myRange
  6. .Font.Bold = False
  7. .ParagraphFormat.Alignment = wdAlignParagraphLeft '左对齐
  8. .Font.Color = wdColorBlack
  9. .Font.name = "黑体"
  10. .Font.Size = 14
  11. .ParagraphFormat.PageBreakBefore = False
  12. .ParagraphFormat.CharacterUnitFirstLineIndent = 0 '去除首行缩进
  13. .ParagraphFormat.FirstLineIndent = CentimetersToPoints(0)
  14. End With
  15. End If
  16. End Sub

(4)表格样式

        修改表格样式,可以查阅开发文档与网络资源。我也参考了AI的一些代码。实现代码如下(最基本的不加样式的表格):

  1. Sub execlOperate() '表格样式操作
  2. Application.ScreenUpdating = False '关闭屏幕刷新
  3. Application.DisplayAlerts = False
  4. On Error Resume Next '忽略错误
  5. Dim mytable As Table, i As Long
  6. If Selection.Information(wdWithInTable) = True Then i = 1
  7. For Each mytable In ActiveDocument.Tables
  8. If i = 1 Then Set mytable = Selection.Tables(1)
  9. With mytable
  10. '取消底色
  11. .Shading.ForegroundPatternColor = wdColorAutomatic
  12. .Shading.BackgroundPatternColor = wdColorAutomatic
  13. Options.DefaultHighlightColorIndex = wdNoHighlight
  14. .Range.HighlightColorIndex = wdNoHighlight
  15. .Style = "表格主题"
  16. '单元格边距
  17. .TopPadding = PixelsToPoints(0, True) '设置上边距为0
  18. .BottomPadding = PixelsToPoints(0, True) '设置下边距为0
  19. .LeftPadding = PixelsToPoints(0, True) '设置左边距为0
  20. .RightPadding = PixelsToPoints(0, True) '设置右边距为0
  21. .Spacing = PixelsToPoints(0, True) '允许单元格间距为0
  22. .AllowPageBreaks = True '允许断页
  23. '.AllowAutoFit = True '允许自动调整尺寸
  24. '设置边框
  25. .Borders(wdBorderLeft).LineStyle = wdLineStyleNone
  26. .Borders(wdBorderRight).LineStyle = wdLineStyleNone
  27. .Borders(wdBorderTop).LineStyle = wdLineStyleNone
  28. .Borders(wdBorderBottom).LineStyle = wdLineStyleNone
  29. .Borders(wdBorderTop).LineStyle = wdLineStyleThinThickMedGap
  30. .Borders(wdBorderTop).LineWidth = wdLineWidth2pt
  31. .Borders(wdBorderBottom).LineStyle = wdLineStyleThickThinMedGap
  32. .Borders(wdBorderBottom).LineWidth = wdLineWidth225pt
  33. With .Rows
  34. .WrapAroundText = False '取消文字环绕
  35. .Alignment = wdAlignRowCenter '表水平居中 wdAlignRowLeft '左对齐
  36. .AllowBreakAcrossPages = False '不允许行断页
  37. .HeightRule = wdRowHeightExactly '行高设为最小值 wdRowHeightAuto '行高设为自动
  38. .Height = CentimetersToPoints(0) '上面缩进量为0
  39. .LeftIndent = CentimetersToPoints(0) '左面缩进量为0
  40. End With
  41. With .Range
  42. With .Font '字体格式
  43. .name = "宋体"
  44. .name = "Times New Roman"
  45. .Color = wdColorAutomatic '自动字体颜色
  46. .Size = 12
  47. .Kerning = 0
  48. .DisableCharacterSpaceGrid = True
  49. End With
  50. With .ParagraphFormat '段落格式
  51. .CharacterUnitFirstLineIndent = 0 '取消首行缩进
  52. .FirstLineIndent = CentimetersToPoints(0) '取消首行缩进
  53. .LineSpacingRule = wdLineSpaceSingle '单倍行距 wdLineSpaceExactly '行距固定值
  54. '.LineSpacing = 20 '设置行间距为20磅,配合行距固定值
  55. .Alignment = wdAlignParagraphCenter '单元格水平居中
  56. .AutoAdjustRightIndent = False
  57. .DisableLineHeightGrid = True
  58. End With
  59. .Cells.VerticalAlignment = wdCellAlignVerticalCenter '单元格垂直居中
  60. End With
  61. '设置首行格式
  62. .Cell(1, 1).Select ' 选中第一个单元格
  63. With Selection
  64. .SelectRow '选中当前行
  65. Selection.Rows.HeadingFormat = wdToggle '自动标题行重复
  66. .Range.Font.Bold = False '表头加粗黑体
  67. .Shading.ForegroundPatternColor = wdColorAutomatic '首行自动颜色
  68. '.Shading.BackgroundPatternColor = -603923969 '首行底纹填充
  69. End With
  70. '自动调整表格
  71. .Columns.PreferredWidthType = wdPreferredWidthAuto
  72. .AutoFitBehavior (wdAutoFitContent) '根据内容调整表格
  73. .AutoFitBehavior (wdAutoFitWindow) '根据窗口调整表格
  74. End With
  75. If i = 1 Then Exit For
  76. Next
  77. Err.Clear: On Error GoTo 0 '恢复错误捕捉
  78. Application.DisplayAlerts = True '开启提示
  79. Application.ScreenUpdating = True '开启屏幕刷新
  80. End Sub

(5)修改图注样式(表注同理)

        修改图注的样式,我的思路是查找所有的图片并获取图片的上一段文本,修改其样式。修改表注同理,实现代码如下。

注:代码中使用了InlineShape库,只能查找Word文档中样式为嵌入式的图片。

  1. Sub GetAllImageNextLineText() '修改所有图注的样式
  2. Dim shp As InlineShape
  3. Dim nextLine As Range
  4. For Each shp In ActiveDocument.InlineShapes
  5. If shp.Type = wdInlineShapePicture Then
  6. Set para = shp.Range.Paragraphs(1)
  7. Set nextPara = para.Next
  8. If Not nextPara Is Nothing Then
  9. '修改下一行文本的样式
  10. With nextPara.Range
  11. .ParagraphFormat.Alignment = wdAlignParagraphCenter '文本居中
  12. .ParagraphFormat.LineSpacingRule = wdLineSpaceSingle '行距
  13. .Font.name = "黑体" '字体名称
  14. .Font.Size = 12 '字体大小
  15. .ParagraphFormat.CharacterUnitFirstLineIndent = 0
  16. .ParagraphFormat.FirstLineIndent = CentimetersToPoints(0)
  17. End With
  18. End If
  19. End If
  20. Next shp
  21. End Sub

(6)页面设置

        这里就罗列的一些常用的页面设置方法,仅供参考和copy。更多详细的属性可自行查阅开发文档。

代码如下:

  1. Sub installPage() '修改页面设置
  2. Dim doc As Document
  3. Set doc = ActiveDocument
  4. With doc.PageSetup
  5. .LineNumbering.Active = False
  6. .Orientation = wdOrientPortrait '页面方向为纵向
  7. .topMargin = CentimetersToPoints(3.3) '上边距
  8. .bottomMargin = CentimetersToPoints(3.3) '下边距
  9. .LeftMargin = CentimetersToPoints(2.8) '左边距
  10. .RightMargin = CentimetersToPoints(2.6) '右边距
  11. .Gutter = CentimetersToPoints(0) '装订线
  12. .HeaderDistance = CentimetersToPoints(1.5) '页眉
  13. .FooterDistance = CentimetersToPoints(1.75) '页脚
  14. .PageWidth = CentimetersToPoints(21) '纸张宽
  15. .PageHeight = CentimetersToPoints(29.7) '纸张高
  16. .FirstPageTray = wdPrinterDefaultBin
  17. .OtherPagesTray = wdPrinterDefaultBin
  18. .SectionStart = wdSectionNewPage '节的起始位置:新建页
  19. .OddAndEvenPagesHeaderFooter = False '不勾选“奇偶页不同”
  20. .DifferentFirstPageHeaderFooter = False '不勾选“首页不同”
  21. .VerticalAlignment = wdAlignVerticalTop '页面垂直对齐方式为“顶端对齐”
  22. .SuppressEndnotes = False '不隐藏尾注
  23. .MirrorMargins = False '不设置首页的内外边距
  24. .TwoPagesOnOne = False
  25. .BookFoldPrinting = False
  26. .GutterPos = wdGutterPosLeft '装订线位于左侧
  27. .LayoutMode = wdLayoutModeLineGrid '版式模式为“只指定行网格”
  28. End With
  29. End Sub

        到此,所有分享结束了,希望上述经历和代码可以帮助你们。还有更多功能和方法值得我和你们去研究,感谢浏览。有其他好的问题和经验可以在评论区留言或私信我。٩(๑❛ᴗ❛๑)۶

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
在移除 Word 文档样式的同时保留格式
在移除 Word 文档样式的同时保留格式 PlatycodonPlatycodon
用金山词霸自动给单词添加音标和解析
VBA Word排版 | VBA实例教程
VSTOword操作
word宏代码集锦
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服