将小时,分钟转换为十进制,并使用VBA基于列值删除行

时间:2018-03-25 06:34:24

标签: excel vba

我想将Excel中的Time Spent列转换为十进制值。

Time Spent

如果输入的值为1小时30分钟,则需要将其转换为1.5(不应附加小时或分钟,只需1.5即可)。如果值为1小时,则值应为1

Q.2)我需要保留名称与特定人员相对应的行。就像我想要维持名称为{Tom Cruise,Brad Pitt,Angelina Jolie,Selena Gomez}的行,以及其他行应该被删除。

如何使用VBA实现这一点。谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情......

Sub ConvertTimeAndDeleteRows()
Dim lr As Long, lc As Long
Dim Rng As Range, Cell As Range

Application.ScreenUpdating = False

lr = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
lc = Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column + 1

Set Rng = Range("C2:C" & lr)

For Each Cell In Rng
    If InStr(Cell.Value, "hour") > 0 Or InStr(Cell.Value, "minutes") > 0 Then
        Cell.Value = StringToTimeDecimals(Cell.Value)
    End If
Next Cell

Range(Cells(2, lc), Cells(lr, lc)).Formula = "=IF(AND(B2<>""Tom Cruise"",B2<>""Brad Pitt"",B2<>""Angelina Jolie"",B2<>""Selena Gomez""),NA(),"""")"
On Error Resume Next
Range(Cells(2, lc), Cells(lr, lc)).SpecialCells(xlCellTypeFormulas, 16).EntireRow.Delete
Columns(lc).Delete
Application.ScreenUpdating = True
End Sub


Function StringToTimeDecimals(ByVal timeStr As String) As Double
    timeStr = Replace(Replace(Replace(timeStr, "hour", ":"), "minutes", ""), " ", "")
    If Right(timeStr, 1) = ":" Then timeStr = timeStr & "00"
    StringToTimeDecimals = TimeSerial(Hour(timeStr), Minute(timeStr), Second(timeStr)) * 24
End Function