我搜索过此代码,但只找到了小时,分钟和秒的输入,并尝试调整找到的代码无效。
我希望用户表单中的输入字段接受3或4位数字作为输入,其中前1或2将分配给分钟,最后2位数分配给分钟的秒数:秒电子表格?
例如。用户输入0523,以5:23的形式传送到excel中的单元格 或者用户输入523,它被转移到excel中的单元格,如5:23
由于
答案 0 :(得分:0)
试试这个:
Private Sub CommandButton1_Click()
Dim tbV As String
Dim sV As String
Dim mV As String
Dim Rng As Range
tbV = Me.TextBox1.Text
If Len(tbV) > 4 Or Len(tbV) < 2 Or Not IsNumeric(tbV) Then
MsgBox "wrong"
Exit Sub
End If
Set Rng = Selection ' change this as you need
sV = Right(tbV, 2)
mV = Left(tbV, Len(tbV) - 2)
Rng.NumberFormat = "m:ss"
Rng.Value = TimeSerial(0, Val(mV), Val(sV))
End Sub
试验:
输入523,结果5:23
输入0523,结果5:23
输入6523,结果5:23(但值为01:05:23)
输入23,结果0:23
答案 1 :(得分:0)
这应该会让你到那里。它会在您键入时检查值并格式化文本框。
'Global variable
Dim bBail as boolean
'Textbox change event
Private Sub TextBox2_Change()
Dim strText As String
Dim oTime As Date
'Check if we are seeing a change because we are setting the value
If bBail = True Then
Exit Sub
End If
'Get the value in the textbox
strText = Trim(TextBox2.Text)
'Take out any semicolons we have in the text
strText = Replace(strText, ":", "")
'Make sure we have valid hours
If Len(strText) > 1 Then
If Val(Left(strText, 2)) > 12 Then
MsgBox ("Invalid Input")
Exit Sub
End If
End If
'Make sure we have valid minutes
If Len(strText) > 3 Then
If Val(Right(strText, 2)) > 59 Then
MsgBox ("Invalid Input")
Exit Sub
End If
End If
'Format for the textbox
If Len(strText) > 2 Then
strText = Left(strText, 2) & ":" & Right(strText, Len(strText) - 2)
End If
'Write the time value to the text box.
bBail = True
TextBox2.Text = strText
bBail = False
End Sub
在文本框按键事件中,我们将确保只能在文本框中输入数字。
Private Sub TextBox2_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'Limit the length of the text. Can be done in textbox properties as well
If Len(TextBox2.Text) > 4 Then
KeyAscii = 0
Exit Sub
End If
If KeyAscii = 8 Then Exit Sub
If Chr(KeyAscii) < "0" Or Chr(KeyAscii) > "9" Then
KeyAscii = 0
End If
End Sub