正如 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