|
本帖最后由 sylun 于 2012-6-22 14:12 编辑
有感于近两天关于中文格式日期转换的帖子(http://club.excelhome.net/thread-484569-1-1.html),花了点时间写了一段转换代码。其基本思路是对查找到的特征文本,经简单筛选再结合Isdate函数的判断来确定有效日期格式文本,最后利用Quote域的日期图片开关来进行相应转换。通过编写这段代码,对Isdate和Datevalue等函数以及Quote域对中文日期的识别有了更多的了解。其适用范围见代码中的相关说明。
欢迎测试并提出改进意见。
- Sub DateFormatConverting()
- ''有选定内容只处理选定部分,否则处理全文档
- ''如选定内容不超过一个段落,则不弹出对话框选择转换类型,程序将根据段落选定内容是否有阿拉伯数字来自动选择转换格式
- ''只转换含“年月日”、“年月”、“月日”或仅为“××××年”四种格式的有效日期文本
- Dim myRange As Range
- Dim a As Integer
- Dim sz As String
- Dim txt As String
- Dim rq As String
- Dim e As Long
- Dim nf As String
- Dim codetext As String
- Dim switch As String
- Dim n As Integer
-
- With Selection
- If .Type = wdSelectionNormal And .Paragraphs.Count = 1 Then
- If .Text Like "*#*" Then a = 6 Else a = 7
- If .Text Like "*[月日]" Then .End = .End + 1 '简单预防性措施
- Else
- a = MsgBox("转为汉字数字日期请按“是”,转为阿拉伯数字日期请按“否”", vbYesNoCancel, "汉字数字与阿拉伯数字中文日期格式转换")
- End If
- Set myRange = IIf(.Type = wdSelectionIP, ActiveDocument.Content, .Range)
- End With
- If a = 2 Then Exit Sub
- sz = IIf(a = 6, "[0-9", "[〇○一二三四五六七八九十")
- Application.ScreenUpdating = False
- With myRange.Duplicate.Find
- .Text = sz & "年月日]{4,}" '不想转换仅为“××××年”的格式文本时可用 .Text = sz & "]@[年月]" & sz & "月日]{2,}"
- .MatchWildcards = True
- Do While .Execute
- With .Parent
- If .Start >= myRange.End - 1 Then Exit Do
- If .Text Like "*?[年月]*" Then
- Do While .Text Like "*" & sz & "][年月日]" = False
- .End = .End - 1
- Loop
- txt = Replace(.Text, "〇", "○")
- If Mid(txt, 3, 1) = "年" Then
- nf = DateValue(Left(txt, InStr(txt, "月")))
- If a = 7 Then nf = IIf(nf Like "1*", "一九", "二○") Else nf = Empty
- End If
- If txt Like "????年" Then
- txt = txt & IIf(a = 6, "1月", "一月")
- switch = IIf(a = 6, " \@ EEEE年", " \@ yyyy年")
- ElseIf a = 7 Then
- switch = IIf(InStr(txt, "日"), IIf(InStr(txt, "年"), " \@ yyyy年M月d日", " \@ M月d日"), " \@ yyyy年M月")
- Else
- switch = IIf(InStr(txt, "日"), IIf(InStr(txt, "年"), " \@ EEEE年O月A日", " \@ O月A日"), " \@ EEEE年O月")
- End If
- rq = Mid(txt, InStr(txt, "月") + 1)
- If Len(rq) = 3 Then
- rq = Left(txt, InStr(txt, "月")) & Replace(rq, "十", "○")
- ElseIf Len(rq) > 3 Then
- rq = Left(txt, InStr(txt, "月")) & Replace(rq, "十", "")
- Else
- rq = txt
- End If
- If IsDate(rq) Then
- codetext = Chr(34) & nf & IIf(InStr(txt, "年"), "", IIf(a = 7, "二〇一二年", "2012年")) & txt & Chr(34)
- If nf <> Empty Then switch = Replace(switch, "yyyy年", "yy年")
- With ActiveDocument.Fields.Add(.Duplicate, wdFieldQuote, codetext & switch, False)
- e = Len(.Result.Text)
- n = n + 1
- .Unlink
- End With
- If Mid(txt, 3, 1) = "年" And a = 6 Then
- ActiveDocument.Range(.Start, .Start + 2).Delete
- e = e - 2
- End If
- .Start = .Start + e
- nf = Empty
- e = 0
- End If
- End If
- End With
- Loop
- End With
- If myRange.Paragraphs.Count > 1 Then MsgBox "OK!共转换了" & n & "个相关日期文本。"
- Application.ScreenUpdating = True
- End Sub
复制代码
|
|