调用sub不工作,但代码在放入正在执行调用的sub中时起作用

时间:2017-03-13 09:17:01

标签: vba excel-vba excel

对于你们来说,这应该是一个快速而简单的人,为什么这不起作用?

代码限制用户仅在文本框中输入文本。 它工作正常,但我有大约50个文本框,所以更干净,更容易打电话。

然而,这样做的限制不再有效

Private Sub OnlyAcceptText()
 'Forces the textbox to only accept text
  If (KeyAscii < 65 Or KeyAscii > 90) And (KeyAscii < 97 Or KeyAscii > 122)Then KeyAscii = 0
End Sub 

KeyPress在文本框中的代码:

Private Sub AgencyContactTextBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'Calls sub that only allows text in texctbox
  Call OnlyAcceptText
End Sub

2 个答案:

答案 0 :(得分:3)

使用事件下沉,你有一个类,里面有一个事件沉没文本框,就像这样

Private WithEvents t As MSForms.TextBox

Public Sub INITIALISE(tb As MSForms.TextBox)
    Set t = tb
End Sub

Private Sub t_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If (KeyAscii < 65 Or KeyAscii > 90) And (KeyAscii < 97 Or KeyAscii > 122) Then KeyAscii =0
End Sub

然后你需要创建一个集合来保存50个类,这些类将模仿me.controls作为集合,但仅用于自定义文本框。

Public colCustomTextboxes As New Collection

Private Sub UserForm_Initialize()
For Each c In Me.Controls
    If TypeName(c) = "TextBox" Then
        set t=new clsCustomTextBox
        t.INITIALISE c
        colCustomTextboxes.Add t
    End If
Next c
End Sub

答案 1 :(得分:2)

关注@Nathan_Sav评论后,您还可以向OnlyAcceptText Sub添加第二个参数,以识别来电者TextBox

Private Sub AgencyContactTextBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

' use can also add the TB as indentifier
OnlyAcceptText AgencyContactTextBox, KeyAscii

End Sub

'========================================================================

Private Sub OnlyAcceptText(ByRef TB As MSForms.TextBox, ByVal KeyAscii As MSForms.ReturnInteger)
    With TB
        If (KeyAscii < 65 Or KeyAscii > 90) And (KeyAscii < 97 Or KeyAscii > 122) Then KeyAscii = 0
    End With
End Sub