Excel VBA格式单元格定制为“h”
我有一个单元格的时间值为1:23:45 AM,并且只想显示小时值或将其用于其他计算。 需要使用vba来做到这一点。 不,我不能手动格式化列。
谢谢,山姆
要使用VBA格式化单元格以仅显示小时:
With Worksheets("Sheet1").Cells(1, 1) .NumberFormat = "H" End With
要读取VBA中的小时值(不pipe格式如何):
Dim hourValue As Integer With Worksheets("Sheet1").Cells(1, 1) If (IsDate(Format(.Value, "hh:mm:ss"))) Then hourValue = Hour(.Value) Else // handle the error End If End With
如果要在代码中使用显示的值,而不在VBA中执行转换,则使用单元格( Range
)的Text
属性而不是Value
属性。 您需要确保单元格格式正确:
Dim hourValue As Integer With Worksheets("Sheet1").Cells(1, 1) If ((.NumberFormat = "H") And _ (IsDate(Format(.Value, "hh:mm:ss")))) Then hourValue = CInt(.Text) Else // handle the error End If End With
如果您只想在工作表公式中使用小时值,则使用HOUR()
工作表函数 – 例如=HOUR(A1)
最后,如果由于工作表受到保护而无法手动格式化列,则无法在VBA中对其进行格式化
我不确定你的手机是不是一个时间字段。 如果是,你可以做以下的事情吗?
dim h as integer h = Hour(Cell(1,1))