我想用VBA做一个Makro,它测量用户按键的时间,例如Space。 当用户停止按下时,存储时间并将其添加到再次按下该键的时间。
我是VBA的新手,并且语法有些问题。所以我找到了keyUP和keyDown函数here,但似乎我以错误的方式使用它。
到目前为止我的代码:
Sub KeyTime()
Time_old = 0
Range("A1").Value = Time_old
If Form_KeyDown(vbKeySpace, 0) Then
Start_time = Timer
If Form_KeyUp(vbKeySpace, 0) Then
End_time = Timer
Time = End_time - Start_time + Time_old
Time_old = Time
Range("A1").Value = Time_old
End If
End If
End Sub
答案 0 :(得分:1)
如果控件具有焦点,则不会触发Userform的键事件。您需要使用全局变量或静态方法来跟踪按键。
这里我在子例程中使用静态数组变量跟踪所有标准键。
Sub CountKeyPresses(KeyAscii As MSForms.ReturnInteger)
Static KeyCounts(255) As Long
If KeyAscii <= 255 Then
KeyCounts(KeyAscii) = KeyCounts(KeyAscii) + 1
Me.Caption = "Key(" & Chr(KeyAscii) & ") was pressed " & KeyCounts(KeyAscii) & " times"
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
CountKeyPresses KeyAscii
End Sub
Private Sub TextBox2_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
CountKeyPresses KeyAscii
End Sub