How can i make a sub for a keypress event?

≯℡__Kan透↙ 提交于 2020-01-25 10:19:07

问题


I'm working on an excel with macros. I have a userform with textboxes, several of them use a function for only press numbers.

Private Sub quantity1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Select Case KeyAscii
        Case Asc("0") To Asc("9")
        Case Else
        KeyAscii = 0
    End Select
End Sub

How can i put the select case on a procedure or function and then call it from any keypress event that i need it (in this case, quantity1 quantity2, price1 and price2, but no in buyer)? I tried making a sub that uses the same parameters like the event e.g:

Sub Only_Numbers(ByVal KeyAscii As MSForms.ReturnInteger)

回答1:


Here is a quick example that I created for you.

Let's say your userform looks like this

Now place this in a class module

Public WithEvents TextBoxEvents As MSForms.TextBox

Private Sub TextBoxEvents_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Select Case KeyAscii
        Case Asc("0") To Asc("9")
        Case Else
            KeyAscii = 0
    End Select
End Sub

Screenshot

And place this in the userform

Dim myTBs() As New Class1

Private Sub UserForm_Initialize()
    Dim i As Integer, objControl As Control

    For Each objControl In Me.Controls
        If TypeOf objControl Is MSForms.TextBox Then
            i = i + 1
            ReDim Preserve myTBs(1 To i)
            Set myTBs(i).TextBoxEvents = objControl
        End If
    Next objControl
    Set objControl = Nothing
End Sub

Screenshot

Now try entering text/numbers in any of the textboxes :)

EDIT

@SiddharthRout Wow! Awesome Reply! it's almost like that, but i require that certain textboxes (not all) on the userform could have this restriction. I guess that if i do this Set myTBs(i).TextBoxEvents = quantity1 (Considering that quantity1 is a textbox) should work? – fjatp 6 mins ago

        If TypeOf objControl Is MSForms.TextBox Then
            Select Case objControl.Name
            Case "TextBox1", "TextBox3", "TextBox4" '<~~ Include only these
                i = i + 1
                ReDim Preserve myTBs(1 To i)
                Set myTBs(i).TextBoxEvents = objControl
            End Select
        End If



回答2:


As a slight modification of Siddharth's code I use collections instead of an array. Anything else remains the same.

Option Explicit

Dim myTBs As New Collection

Private Sub UserForm_Initialize()
    Dim i As Integer, objControl As Control
    Dim TB As Class1

    For Each objControl In Me.Controls
        If TypeOf objControl Is MSForms.TextBox Then
            Set TB = New Class1
            Set TB.TextBoxEvents = objControl
            myTBs.Add TB
        End If
    Next objControl
    Set objControl = Nothing
End Sub


来源:https://stackoverflow.com/questions/51665993/how-can-i-make-a-sub-for-a-keypress-event

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