Time format of text box in excel user form

孤街浪徒 提交于 2020-01-17 07:59:29

问题


I have below code to set time format of atext box "txtA" in userform.

Private Sub txtA_Afterupdate()
Dim tString As String
 With txtA

'Check if user put in a colon or not
 If InStr(1, .Value, ":", vbTextCompare) = 0 And Len(.Value) > 1 Then

'If not, make string 4 digits and insert colon
 tString = Format(.Value, "0000")
 tString = Left(tString, 2) & ":" & Right(tString, 2)
 txtA.Value = Format(TimeValue(tString), "hh:mm")
Else

'Otherwise, take value as given
 .Value = Format(.Value, "hh:mm")
End If
End With

Assume I have say 20 text boxes,(A - E) make one group (F- H)make another group and so on. now I have 2 Q. 1-Should i apply above code to each textbox individually or there's a code that i just can put all text boxes name of userform in it? 2- with input data higher than 23:59 it gives error i changed the format to [h]:mm but didn't work,I want if user enters 35:45 the time be shown as it is not like d:hh:mm


回答1:


The answer to question 1 is that you need to apply the code to every textbox but first you should take the code that you have and make it a function that you can call from each txt$_Afterupdate() sub.

The function will need to know which textbox to format so it will have to receive the textbox object

function formatTime(objTXT As Object)

then in the code replace txtA with objTXT

objTXT.Value = Format(TimeValue(tString), "hh:mm")

then you will call formatTime from each textbox Afterupdate and pass the textbox object.

Private Sub txtA_Afterupdate()

    formatTime me.txtA

end sub

I need to think about your second question but I'm pretty sure that you can't use the format hh:mm if you want to accept more than 24 hours.



来源:https://stackoverflow.com/questions/42374948/time-format-of-text-box-in-excel-user-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!