我正在使用宏处理Excel。我有一个带有文本框的用户窗体,其中一些使用仅用于按数字的功能。
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
如何将选择大小写放在过程或函数上 然后从我需要它的任何按键事件中调用它(在这种情况下,数量1数量2,价格1和价格2,但在买方中没有)? 我尝试制作一个使用与事件等参数相同的子对象:
Sub Only_Numbers(ByVal KeyAscii As MSForms.ReturnInteger)
答案 0 :(得分:2)
这是我为您创建的一个简单示例。
假设您的用户表单如下
现在将其放置在类模块中
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
屏幕截图
并将其放在用户表单中
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
屏幕截图
现在尝试在任何文本框中输入text/numbers
:
编辑
@SiddharthRout哇!很棒的回复!几乎就像那样,但是我要求用户窗体上的某些文本框(不是全部)可以有此限制。我想如果我这样做Set myTBs(i).TextBoxEvents = Quantity1(考虑quantity1是文本框)应该可以工作? – 6分钟前fjatp
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
答案 1 :(得分:0)
作为对Siddharth代码的略微修改,我使用集合而不是数组。其他都保持不变。
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