在单元格中搜索一小时的文本并将小时复制到VBA中的其他单元格

时间:2016-06-28 08:15:40

标签: vba excel-vba excel

我已经为1200行提供了数据库,我希望在单元格中搜索一小时的笔记,并将特定小时复制到另一个单元格。

例如,在单元格I中有这样的数据: "我等到6:45的公共汽车站的公共汽车,然后乘坐了#34;

我得到的是:

Sub Find()
irow = 2
    Do Until IsEmpty(Cells(irow, 34))
        If Cells(irow, 34).Value Like "*[0-23]:[0-59]*" = True Then
            Cells(irow, 34).Value = Cells(irow, 37).Value
            irow = irow + 1
        Else
            irow = irow + 1
        End If
    Loop
End Sub

谢谢!

2 个答案:

答案 0 :(得分:1)

而不是

If Cells(irow, 34).Value Like "*[0-23]:[0-59]*" = True Then

If Cells(irow, 34).Value Like "*#:##*" Then

您还可以使用以下代码:

Sub Find()
    Dim i As Integer
    Dim arr() As String

    irow = 2
    Do Until IsEmpty(Cells(irow, 34))
        arr = Split(Cells(irow, 34), " ")
        For i = LBound(arr) To UBound(arr)
            If IsTime(arr(i)) Then
                'to get the hour
                MsgBox Left(arr(i), Application.WorksheetFunction.Find(":", arr(i)) - 1)
                Cells(irow, 34).Value = Cells(irow, 37).Value
                Exit For
            End If
        Next
        irow = irow + 1
    Loop
End Sub

Function IsTime(strData As String) As Boolean
    On Error Resume Next
    IsTime = TimeValue(strData)
End Function

答案 1 :(得分:0)

以下代码在文本中查找时间戳,并将其写入同一行的单独列中。但是它假定只有一个序列为" [数字] [数字]:[数字] [数字]"存在。如果您的输入可能有多个,则可能需要一些额外的过滤条件。

但首先,您需要确保在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