|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
用自定义函数做,效果如下——
自定义函数的代码如下——
- Option Explicit
- Function SumMonths(rngCritera As Range, rngData As Range)
- Dim datStart As Date, datEnd As Date, strTemp$, k As Range, d1 As Date, d2 As Date
- If InStr(rngCritera.Value, "至") > 0 Then
- datStart = CDate(RegTest(rngCritera.Value, "\d{4}年\d+月\d+日", 0))
- datEnd = CDate(RegTest(rngCritera.Value, "\d{4}年\d+月\d+日", 1))
- ElseIf InStr(rngCritera.Value, "前") > 0 Or InStr(rngCritera.Value, "底") > 0 Then
- datStart = DateSerial(1900, 1, 1)
- strTemp = RegTest(rngCritera.Value, "(\d{4}年\d+月\d+日.)|(\d{4}年后)|(\d{4}年\d+月.)", 0)
- strTemp = Replace(strTemp, "月底", "月28日底")
- strTemp = Replace(strTemp, "月前", "月28日前")
- datEnd = CDate(Left(strTemp, Len(strTemp) - 1))
- ElseIf InStr(rngCritera.Value, "后") > 0 Then
- strTemp = RegTest(rngCritera.Value, "(\d{4}年\d+月\d+日后)|(\d{4}年后)|(\d{4}年\d+月后)", 0)
- strTemp = Replace(strTemp, "年后", "年1月1日后")
- datStart = CDate(Left(strTemp, Len(strTemp) - 1))
- datEnd = Date
- End If
- If Day(datStart) > 1 Then datStart = DateSerial(Year(datStart), Month(datStart) + 1, 1)
- If Day(datEnd) > 1 Then datEnd = DateSerial(Year(datEnd), Month(datEnd) + 1, 1)
- For Each k In rngData.Columns(1).Cells
- If Len(k.Value) > 0 Then
- d1 = Application.Max(datStart, CDate(Format(k.Value, "0000年00月")))
- d2 = Application.Min(datEnd, DateAdd("m", 1, CDate(Format(k.Offset(0, 1).Value, "0000年00月"))))
- SumMonths = SumMonths + IIf(d1 < d2, DateDiff("m", d1, d2), 0)
- End If
- Next
- End Function
- Function RegTest(strText As String, strPattern As String, intItem As Integer)
- '定义正则表达式对象
- Dim oRegExp As Object
- '定义匹配字符串集合对象
- Dim oMatches As Object
- '创建正则表达式
- Set oRegExp = CreateObject("vbscript.regexp")
- With oRegExp
- '设置是否匹配所有的符合项,True表示匹配所有, False表示仅匹配第一个符合项
- .Global = True
- '设置是否区分大小写,True表示不区分大小写, False表示区分大小写
- .IgnoreCase = True
- '设置要查找的字符模式
- .Pattern = strPattern
- '对字符串执行正则查找,返回所有的查找值的集合,若未找到,则为空
- Set oMatches = .Execute(strText)
- RegTest = oMatches(intItem)
- End With
- Set oRegExp = Nothing
- Set oMatches = Nothing
- End Function
复制代码
|
|