如何限制用户在Excel用户表单的所有文本框中只能输入数字

问题描述 投票:0回答:1

我的 Excel 用户表单中有 60 个文本框。为了限制用户仅在 TextBox1 到 TextBox50 中输入数字(十进制),我需要编写大量如下相同的代码。

我的问题:

1.我想创建一个类/函数,就好像我不需要为 TextBox1 到 TextBox50 编写相同的代码一样。有简单的解决办法吗?

2.如果我想限制用户在用户表单的所有文本框中输入数字。

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If (KeyAscii > 47 And KeyAscii < 58) Or KeyAscii = 46 Then
KeyAscii = KeyAscii
Else
KeyAscii = 0
End If
End Sub

Private Sub TextBox2_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'same code
End Sub

    .......
    .......
excel vba textbox userform
1个回答
2
投票

请尝试下一个方法:

  1. 插入一个类模块作为事件包装类并将其命名为“TxtBClass”,然后复制其模块中的下一个代码:
Option Explicit

Public WithEvents txtBEvent As MSForms.TextBox


Private Sub txtBEvent_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
  If (KeyAscii > 47 And KeyAscii < 58) Or KeyAscii = 46 Then
      KeyAscii = KeyAscii
  Else
      KeyAscii = 0
  End If
End Sub
  1. 将下一个代码粘贴到标准模块中:
Option Explicit

Private txtB() As New TxtBClass

Sub AssignTxtBoxEvent()
  Dim ws As Worksheet, k As Long, oObj As OLEObject
  
  Set ws = ActiveSheet 'use here your necessary sheet
  ReDim txtB(100) 'maximum text boxes to be processed (can be increased)
  
  For Each oObj In ws.OLEObjects
    If TypeName(oObj.Object) = "TextBox" Then
        'exclude the textboxes you need to be excluded from this common event:
        If (oObj.Name <> "TextBoxX") And (oObj.Name <> "TextBoxX") Then
            Set txtB(k).txtBEvent = oObj.Object: k = k + 1
        End If
    End If
   Next
   ReDim Preserve txtB(k - 1)
End Sub
  1. 运行上面的
    Sub
    ,以便在工作表上的所有文本框上分配事件。它也可以由事件调用(或者更好)。例如,使用
    Worksheet_Activate
    事件。请复制工作表中的下一个代码,保留文本框,代码模块:
Option Explicit

Private Sub Worksheet_Activate()
    AssignTxtBoxEvent
End Sub
  1. 请测试建议的解决方案并发送一些反馈。

已编辑

为了对用户窗体中文本框的情况使用建议的解决方案,请保留相同的类,但将其事件分配给

UserForm_Initialize
事件内涉及的文本框:

Option Explicit

Private txtB() As New TxtBClass
Private Sub UserForm_Initialize()
  Dim k As Long, oObj As Control
  ReDim txtB(100) 'maximum text boxes to be processed (it can be increased)
  
  For Each oObj In Me.Controls
    If TypeName(oObj) = "TextBox" Then
        'exclude the textboxes you need to be excluded from this common event:
        If (oObj.Name <> "TextBoxX") And (oObj.Name <> "TextBoxY") Then
            Set txtB(k).txtBEvent = oObj: k = k + 1
        End If
    End If
   Next
   ReDim Preserve txtB(k - 1)
End Sub

请测试它并发送一些反馈。如果今年的话,将不胜感激...

© www.soinside.com 2019 - 2024. All rights reserved.