MACRO将字符串时间格式转换为分钟

时间:2016-07-14 03:39:40

标签: excel-vba vba excel

REFER IMAGE

在那张图片中,我希望将1小时41分钟转换为101分钟。请用宏观VBA帮助我。

1 个答案:

答案 0 :(得分:0)

正如布莱恩戴维斯所提到的,你可以用公式做到这一点。

假设初始文本的格式始终与图像中显示的一致,则以下公式应该有效: =(LEFT(A1,FIND("hr",A1)-1)*60)+MID(A1,FIND("hr",A1)+3,3) & " mins"

当然,如果你坚持使用宏,下面的代码可以用来转换活动单元格(宏可以更好地工作,因为它接受更灵活的格式化(例如“1小时10分钟”与宏一起工作但是不符合公式)):

Sub ConvertToMins()
    Dim mins As Integer
    Dim SearchString  As String
    Dim hourLength As Integer
    Dim minPos As Integer

    mins = 0
    SearchString = ActiveCell.Text

    If InStr(1, SearchString, " h", vbTextCompare) <> 0 Then
        hourLength = InStr(1, SearchString, " h", vbTextCompare) - 1
    ElseIf InStr(1, SearchString, "h", vbTextCompare) <> 0 Then
        hourLength = InStr(1, SearchString, "h", vbTextCompare) - 1
    Else
        Exit Sub
    End If

    mins = mins + (CDbl(Left(SearchString, hourLength)) * 60)

    If InStr(1, SearchString, " m", vbTextCompare) <> 0 Then
        minPos = InStr(1, SearchString, " m", vbTextCompare) - 2
    ElseIf InStr(1, SearchString, "m", vbTextCompare) <> 0 Then
        minPos = InStr(1, SearchString, "m", vbTextCompare) - 2
    Else
        ActiveCell.Value = CStr(mins) & " mins"
        Exit Sub
    End If

    If IsNumeric(Mid(SearchString, minPos, 2)) = True Then
        mins = mins + (CInt(Mid(SearchString, minPos, 2)))
    Else
        mins = mins + (CInt(Mid(SearchString, minPos, 1)))
    End If

    ActiveCell.Value = CStr(mins) & " mins"
End Sub