Word VBA快速制作试卷(2/2)

实例需求:英语听力题目及其答案(题目编号之前括号内字母为答案)如下所示。

在这里插入图片描述

现在需要将文档整理为如下格式:

  • 第一部分为听力题目,擅长每个题目编号之前的答案(包含括号)
  • 增加一个段落“参考答案”
  • 第3部分为听力题目含参考答案,并修改英语如下格式
    – 题目编号之前的答案应用红色字体
    – 题目答案选项应用红色字体和下划线

其效果如下图所示。

在这里插入图片描述

Sub Demo()
    Dim oDoc As Document: Set oDoc = ActiveDocument
    Dim oRng As Range: Set oRng = oDoc.Range
    Dim iEnd As Long: iEnd = oRng.End
    oRng.Copy
    oRng.InsertParagraphAfter
    oRng.Paragraphs.Last.Range.ListFormat.RemoveNumbers NumberType:=wdNumberParagraph
    oRng.Characters.Last.InsertAfter vbCr & "参考答案" & vbCr
    oRng.Collapse Direction:=wdCollapseEnd
    oRng.Paste
    Dim pasteRange As Range
    Set pasteRange = oRng
    If pasteRange.ListFormat.ListType <> wdListNoNumbering Then
        pasteRange.ListFormat.ApplyListTemplate ListTemplate:=ListGalleries(wdNumberGallery).ListTemplates(1), ContinuePreviousList:=False
    End If
    Dim oAnswer As Range, sAnswer As String
    With pasteRange.Find
        .ClearFormatting
        .Wrap = wdFindStop
        .MatchWildcards = True
        .Text = "\( [A-Z] \)"
        Do While .Execute
            With .Parent
                sAnswer = Trim(Mid(.Text, 2, Len(.Text) - 2))
                Set oAnswer = .Paragraphs(1).Next.Range
                .Font.ColorIndex = wdRed
            End With
            With oAnswer.Find
                .ClearFormatting
                .Wrap = wdFindStop
                .MatchWildcards = True
                .Text = sAnswer & "\. <*>\."
                .Replacement.Font.ColorIndex = wdRed
                .Replacement.Font.Underline = wdUnderlineSingle
                .Execute Replace:=wdReplaceAll
            End With
        Loop
    End With
    Set oRng = oDoc.Range(0, iEnd)
    With oRng.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "\( [A-Z] \)"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
        .Execute Replace:=wdReplaceAll
    End With
End Sub

【代码解析】
第2行代码获取当前活动文档对象,并赋值给变量 oDoc。
第3行代码获取整个文档的范围Range对象,用于后续内容操作。
第4行代码记录当前文档末尾位置的字符索引,用于后续定位处理前的内容(即原始文档内容)。
第5行代码将整个文档复制到剪贴板。
第6行代码在文档末尾插入一个新的段落,以便后续插入答案内容。
第7行代码移除最后一个段落中可能存在的编号格式,确保复制内容时格式统一。
第8行代码在文档末尾插入段落标记和“参考答案”(作为一个单独段落),用于标识复制内容的开始。
第9行代码将范围折叠到末尾,准备粘贴剪贴板中的内容。
第10行代码将先前复制的内容粘贴到“参考答案”段落之后。
粘贴操作完成之后,oRng对象将代表新粘贴的文档内容,即oRng的范围发生了变化。
第11行代码定义一个新的范围对象 pasteRange,用于表示刚刚粘贴的答案区域。
第12行代码将 pasteRange 设置为粘贴内容。
第13-15行代码判断 pasteRange 是否存在编号,如果存在则重新应用编号样式,使粘贴内容具有统一格式。

第16行代码定义两个变量用于存储当前查找到的答案内容和操作范围。
第21行代码配置查找条件,使用通配符查找模式\( [A-Z] \),查找形如( A )的选项格式。
第22~37行代码为查找循环,逐个处理答案标记。
第23~27行代码提取选项字母(去除括号),并标红原始答案位置。
第28-36行代码在答案区域查找与选项内容匹配的题干项(如 A. 正确),将其字体颜色设置为红色,并加下划线,标示正确答案。

第39行代码重新设置范围对象 oRng 为从文档开头到原始末尾(iEnd)之前的内容(即不包括新粘贴的“参考答案”及其之后的内容),准备查找操作。
第43~44行代码设置查找条件,并将其替换为空字符串,删除所有题目前的答案选项编号。
第54行执行全部替换。

使用 **Excel VBA**(Visual Basic for Applications)也可以实现以 Excel 表格为数据库,以 Word 文档为模板来生成试卷的程序。VBA 是 Excel 内置的一种编程语言,适合用于自动化 Excel 和 Word 的操作。 --- ### ✅ 功能目标 - 使用 Excel 表格作为题库数据库。 - 使用 Word 文档作为试卷模板。 - 从 Excel 中读取题目内容。 - 将题目填充到 Word 模板中,生成完整的试卷文档。 --- ### ✅ Excel 表格结构示例(Sheet1) | 题目内容 | 选项A | 选项B | 选项C | 选项D | 答案 | |----------|-------|-------|-------|-------|------| | 中国首都是哪里? | 北京 | 上海 | 广州 | 深圳 | A | | ... | ... | ... | ... | ... | ... | --- ### ✅ VBA 程序代码(在 Excel 中编写) ```vba Sub GenerateExamPaper() Dim wdApp As Object, wdDoc As Object Dim ws As Worksheet Dim LastRow As Long, i As Long Dim TemplatePath As String Dim OutputPath As String ' 设置工作表 Set ws = ThisWorkbook.Sheets("Sheet1") ' 请根据实际修改工作表名称 LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' 获取最后一行 ' 创建 Word 应用程序 On Error Resume Next Set wdApp = GetObject(, "Word.Application") If wdApp Is Nothing Then Set wdApp = CreateObject("Word.Application") On Error GoTo 0 ' 设置模板路径和输出路径 TemplatePath = "C:\YourPath\template.docx" ' 替换为你的 Word 模板路径 OutputPath = "C:\YourPath\exam_paper.docx" ' 替换为输出路径 ' 打开 Word 模板 Set wdDoc = wdApp.Documents.Add(TemplatePath) wdApp.Visible = True ' 显示 Word 窗口,方便查看生成过程 ' 添加标题 wdDoc.Content.InsertAfter "试卷" & vbCrLf wdDoc.Content.Paragraphs(wdDoc.Content.Paragraphs.Count).Range.Style = "Heading 1" ' 循环插入题目 For i = 2 To LastRow ' 假设第一行为标题 With ws wdDoc.Content.InsertAfter i - 1 & ". " & .Cells(i, 1).Value & vbCrLf wdDoc.Content.InsertAfter "A. " & .Cells(i, 2).Value & vbCrLf wdDoc.Content.InsertAfter "B. " & .Cells(i, 3).Value & vbCrLf wdDoc.Content.InsertAfter "C. " & .Cells(i, 4).Value & vbCrLf wdDoc.Content.InsertAfter "D. " & .Cells(i, 5).Value & vbCrLf wdDoc.Content.InsertAfter "答案:____________________" & vbCrLf & vbCrLf End With Next i ' 保存并关闭文档 wdDoc.SaveAs2 OutputPath MsgBox "试卷已生成至:" & OutputPath End Sub ``` --- ### ✅ 使用说明 1. 打开 Excel 文件,按 `Alt + F11` 打开 VBA 编辑器。 2. 插入一个模块(`Insert > Module`)。 3. 将上面的代码粘贴进去。 4. 修改以下路径: ```vba TemplatePath = "C:\YourPath\template.docx" OutputPath = "C:\YourPath\exam_paper.docx" ``` 5. 在 Excel Sheet1 中填写题目数据。 6. 运行宏(按 `F5` 或通过“开发工具”菜单运行)。 --- ### ✅ Word 模板建议 - 可以设置好页眉、页脚、字体样式。 - 模板文件可以是空的 `.docx` 文件,程序会自动添加内容。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值