以下代码在文本中查找时间戳,并将其写入同一行的单独列中。但是,它假定只有一个“[数字] [数字]:[数字] [数字]”序列存在。如果您的输入可能有多个您可能需要一些额外的筛选条件。
但首先您需要确保在VBA项目中激活正则表达式。 (见here)
Sub Find()
my_row = 1
my_column = 1
Dim regEx As New RegExp
regEx.Pattern = "\d*\d:\d\d"
regEx.IgnoreCase = True 'True to ignore case
regEx.Global = True 'True matches all occurances, False matches the first occura
Do Until IsEmpty(Cells(my_row, my_column))
If regEx.Test(Cells(my_row, my_column)) Then
Debug.Print ("Found something")
Dim matches
Set matches = regEx.Execute(Cells(my_row, my_column))
If matches.Count = 1 Then
Cells(my_row, my_column + 2).Value = matches(0).Value
Else
Debug.Print ("Warning more than one match found")
End If
Else
Debug.Print ("Nothing found")
End If
my_row = my_row + 1
Loop
End Sub
我用下面的行测试代码:
I wait to the bus in the bus a92ohr2902 stop for the ride of 6:58 and the ride did'nt stop
I wait to the bus in the bus ;3;23576;80-934 stop for the ride of 6:59 and the ride did'nt stop
I wait to the bus in the bus 2016-06-01 stop for the ride of 14:00 and the ride did'nt stop
I wait to the bus in the bus 9023845 stop for the ride of 14:01 and the ride did'nt stop
I wait to the bus in the bus ;3;23576;80-934 stop for the ride of 20:50 and the ride did'nt stop
I wait to the bus in the bus 2016-06-01 stop for the ride of 20:59 and the ride did'nt stop
I wait to the bus in the bus 9023845 stop for the ride of 21:00 and the ride did'nt stop
I wait to the bus in the bus a92ohr2902 stop for the ride of 21:01 and the ride did'nt stop
它看起来不错,但如果我已经在特定的单元格其他号码?像这样:“我在公共汽车站等待6点57分乘坐公共汽车254,并且乘车没有停止” – user3306637
@ user3306637没错,在这种情况下,代码由[Mrig]提供(http:// stackoverflow .com/a/38072190/637466)似乎更好地将时间戳与其他数字分开。 – aPhilRa
Mrig的代码不起作用。你的代码工作很好,只需要检查这个问题。 – user3306637