20170724wdVBA正则表达式提取答案到Excel

Public Sub RegExtractData()
    Dim StartTime, UsedTime
    StartTime = VBA.Timer

    Dim FilePath$
    Dim FileName$
    Dim doc As Document
    Dim Arr() As String
    Dim ExamNo As String
    Dim Index As Long
    Dim Count As Long

    Dim xlApp As Object    'Excel.Application
    Dim wb As Object    'Excel.Workbook
    Dim sht As Object    'Excel.Worksheet
    Dim Reg As Object, Mh As Object, OneMh As Object
    Set Reg = CreateObject("Vbscript.Regexp")
    With Reg
        .MultiLine = True
        .Global = True
        .Ignorecase = False
    End With

    Application.ScreenUpdating = False
    Application.DisplayAlerts = wdAlertsNone

    FilePath = ThisDocument.Path & "\试卷\"
    FileName = Dir(FilePath & "*.doc*")

    Count = 0
    ReDim Arr(1 To 3, 1 To 1)

    Do While FileName <> ""
        Debug.Print FilePath & FileName
        Set doc = Application.Documents.Open(FilePath & FileName)
        Index = 0
        Content = doc.Content.Text

        '试卷编号:0199
        Reg.Pattern = "(?:试卷编号:)(\S+?)(?:[\s]+?)"
        Set Mh = Reg.Execute(Content)
        ExamNo = "'" & Mh.Item(0).submatches(0)
        Debug.Print ExamNo

        '答案:A|B|C
        Reg.Pattern = "(?:答案:)(\S+?)(?:[\s]+?)"
        Set Mh = Reg.Execute(Content)
        For Each OneMh In Mh
            Index = Index + 1
            Count = Count + 1
            ReDim Preserve Arr(1 To 3, 1 To Count)
            Arr(1, Count) = ExamNo
            Arr(2, Count) = Index
            Arr(3, Count) = OneMh.submatches(0)
        Next OneMh

        doc.Close
        FileName = Dir
    Loop

    Set Reg = Nothing

    Application.ScreenUpdating = True
    Application.DisplayAlerts = wdAlertsAll

    Set xlApp = CreateObject("Excel.Application")    'Excel.Application
    With xlApp
        Set wb = xlApp.Workbooks.Add   'Open(ThisDocument.Path & "\" & "答案模板.xls")
        With wb
            Set sht = .Worksheets("Sheet1")
            With sht
                .Range("A1:C1").Value = Array("试卷编号", "题号", "答案")
                .Range("A2").Resize(Count, 3).Value = xlApp.WorksheetFunction.Transpose(Arr)
            End With
            'xlApp.WorksheetFunction.Transpose (Arr)
            .SaveAs ThisDocument.Path & "\" & Format(Now(), "yyyymmdd-hhmm") & "-答案.xls"
            .Close True
        End With
        .Quit
    End With

    Set xlApp = Nothing
    Set wb = Nothing
    Set sht = Nothing
    UsedTime = VBA.Timer - StartTime
    MsgBox "提取完成!用时" & Format(UsedTime, "0.00 秒。")

End Sub

  

转载于:https://www.cnblogs.com/nextseven/p/7227702.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值