0

宏在选择运行时采用显示为 20130808191057 的日期时间并将其格式化为 19:10 IT。

该宏效果很好,但如果我要选择包含空单元格的单元格范围,它将停止并出现错误。我怎样才能让它忽略空单元格和带有文本的单元格。如果可能,我想在选定的列上运行它。

Sub TimeCreator()
    Dim r As Range, t As String
    For Each r In Selection
        t = r.Text
        r.Clear
        r.Value = TimeSerial(Mid(t, 9, 2), Mid(t, 11, 2), Right(t, 2))
        r.NumberFormat = "[h]:mm  ""IT"""
    Next
End Sub

提前致谢。

4

1 回答 1

1

正如 Andy G 所说 - 您需要检查单元格是否为空,如果是则跳过。

你可以这样做:

Sub TimeCreator()
    Dim r As Range, t As String
    For Each r In Selection
        If r.Value <> Empty Then 'test if the cell is blank (note, a zero length string is not blank in Excel)
            t = r.Text
            'r.Clear is unnecessary as you assign to r.Value
            r.Value = TimeSerial(Mid(t, 9, 2), Mid(t, 11, 2), Right(t, 2))
            r.NumberFormat = "[h]:mm  ""IT"""
        End If
    Next
End Sub

但是,最好只在首先具有值的单元格上运行宏,您可以使用 Range.SpecialCells() 来执行此操作,例如:

Sub TimeCreator()
    Dim r As Range, rangeToRunOn As Range, t As String
    Set rangeToRunOn = Selection.SpecialCells( _
                           xlCellTypeConstants, _
                           xlTextValues OR xlNumbers)
    If Not rangeToRunOn is Nothing Then
        For Each r In rangeToRunOn
            t = r.Text
            'r.Clear is unnecessary as you assign to r.Value
            r.Value = TimeSerial(Mid(t, 9, 2), Mid(t, 11, 2), Right(t, 2))
            r.NumberFormat = "[h]:mm  ""IT"""
        Next
    End If
End Sub
于 2013-08-11T13:39:38.180 回答