VBA正则expression式匹配时间范围,如“1:30 pm – 12:00 am”

我正在尝试使用VBA正则expression式来validation窗体的时间范围: #0:00xm - #0:00xm其中xap 。 所以string文字可以是"1:30pm - 12:00am" 。 我想匹配有这种模式的细胞。

当我在这个在线工具中使用正则expression式时: http://public.kvalley.com/regex/regex.asp : http://public.kvalley.com/regex/regex.asp并检查我的expression式,它正确匹配。

但是,当我在VBA中使用相同的expression式时,它不匹配。

 Dim rRange As Range Dim rCell As Range Set rRange = Range("A2", "A4") '"G225") For Each rCell In rRange.Cells MsgBox (rCell.Value) If rCell.Value Like "^([0-9]{1,2}[:][0-9]{2}[apm]{2}[ ][-][ ][0-9]{1,2}[:][0-9]{2}[apm]{2})$" Then MsgBox ("YES") 'rCell.Interior.Color = RGB(0, 250, 0) Else MsgBox ("NO") 'rCell.Interior.Color = RGB(250, 0, 0) End If Next rCell 

对于任何关心的人来说,这是我的固定工作版本,特别感谢dda,他的简单的RegEx ^^:

 Dim rRange As Range Dim rCell As Range Dim re As Object Set re = CreateObject("vbscript.regexp") With re .Pattern = "^\d\d?:\d\d[aApP][mM] - \d\d?:\d\d[aApP][mM]$" .Global = False .IgnoreCase = False End With Set rRange = Range("A2", "G225") For Each rCell In rRange.Cells If re.Test(rCell) Then rCell.Interior.Color = RGB(0, 250, 0) Else rCell.Interior.Color = RGB(250, 0, 0) End If Next rCell 

让我们来清理并改进你的正则expression式:

 ^\d\d?:\d\d[aApP][mM] - \d\d?:\d\d[aApP][mM]$ 

这只会匹配,如果整个单元格格式化为你想要的date,没有别的(^ _ ___ $条件)。 我加了一个和A,P和P,以确保没有任何大小写问题。

我没有这台机器上的VBA / Excel,所以不能用我的正则expression式尝试你的代码,但正则expression式本身的作品。

在Excel内部,转到格式单元格>数字>类别>自定义。 你会看到很多时间格式。

你可能正在寻找的是:上午/下午

好的。 我更仔细地考虑了这一点,并实现了我的短视。

这更多的是你以后? 我对AM / PM格式化的时间值和没有格式化的单元格进行了基本testing。

 Dim rRange As Range Dim rCell As Range Set rRange = Range("A2", "A4") For Each rCell In rRange If InStr(1, UCase(rCell.Value), " AM") > 0 Or InStr(1, UCase(rCell.Value), " PM") > 0 Then If InStr(1, rCell.Value, ":") <> 0 Then Debug.Print rCell.Value End If Next