excel,从excel表格中的一个单元格提取时间间隔?

时间:2018-09-11 11:36:14

标签: excel vba excel-vba excel-formula

我有一个如下所示的Excel工作表,即使只想删除每个单元格中的三个Break以外的所有内容,我也只需要三个“ Break” 时间即可。

excel sheet like this

Function GetBreaksTime(txt As String)
    Dim i As Long
    Dim arr As Variant

    arr = Split(txt, "Break")
    If UBound(arr) > 0 Then
        ReDim startTimes(1 To UBound(arr)) As String
        For i = 1 To UBound(arr)
            startTimes(i) = WorksheetFunction.Trim(Replace(Split(arr(i), "-")(0), vbLf, ""))
        Next
        GetBreaksTime = startTimes
    End If  
End Function

这是我到现在为止得到的,但是它不能在每个单元格上工作,并且它采用错误的值。

所以知道怎么做吗?

1 个答案:

答案 0 :(得分:1)

如果您将单元格值除以vbLf,则中断时间将始终遵循包含"Break"的行。

以下方法应该起作用:

Sub TestGetBreakTimes()
    Dim CellValue As String
    CellValue = Worksheets("Sheet1").Range("A1").Value

    Dim BreakTimes As Variant
    BreakTimes = GetBreakTimes(CellValue)

    Debug.Print Join(BreakTimes, vbLf)  'the join is just to output the array at once.

    'to output in different cells loop through the array
    Dim i As Long
    For i = 0 To UBound(BreakTimes)
        Cells(3 + i, "A") = BreakTimes(i)
    Next i

    'or for a even faster output use
    Range("A3").Resize(UBound(BreakTimes) + 1).Value = WorksheetFunction.Transpose(BreakTimes)
End Sub

Function GetBreakTimes(InputData As String) As Variant
    Dim BreakTimes() As Variant
    ReDim BreakTimes(0)

    Dim SplitArr As Variant
    SplitArr = Split(InputData, vbLf) 'split by line break

    If UBound(SplitArr) > 0 Then
        Dim i As Long
        For i = 0 To UBound(SplitArr)
            If SplitArr(i) = "Break" Then 'if line contains break then next line is the time of the break
                If BreakTimes(0) <> vbNullString Then ReDim Preserve BreakTimes(UBound(BreakTimes) + 1)
                BreakTimes(UBound(BreakTimes)) = SplitArr(i - 1) 'collect break time
            End If
        Next i
        GetBreakTimes = BreakTimes
    End If
End Function

要分析完整范围,您必须遍历第2行

Sub GetAllBreakTimes()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    Dim LastCol As Long
    LastCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column

    Dim BreakTimes As Variant

    Dim iCol As Long
    For iCol = 1 To LastCol
        BreakTimes = GetBreakTimes(ws.Cells(2, iCol).Value)
        ws.Cells(3, iCol).Resize(UBound(BreakTimes) + 1).Value = WorksheetFunction.Transpose(BreakTimes)
    Next iCol
End Sub