在Excel VBA中合并私人小组函数

我已经写了三个不同的私人小组函数,所有这些都做同样的事情私人小组txt_noRooms_KeyPress私人小组txt_length_KeyPress确保用户只能键入值1至9到引用的文本字段,而私人小组txt_studentNo_KeyPress允许用户input值0到9到引用的文本字段中。

有什么办法可以合并这三个函数,让他们仍然支持引用的单元格,并保持相同的条件? 我想这样做是为了使代码更有效率。

Private Sub txt_noRooms_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) ' Restrict entry to txt_noRooms Select Case KeyAscii Case Asc("1") To Asc("9") Case Asc("-") If InStr(1, Me.txt_noRooms.Text, "-") > 0 Or Me.txt_noRooms.SelStart > 0 Then KeyAscii = 0 End If Case Asc(".") If InStr(1, Me.txt_noRooms.Text, ".") > 0 Then KeyAscii = 0 End If Case Else KeyAscii = 0 End Select End Sub Private Sub txt_length_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) ' Restrict entry to txt_length Select Case KeyAscii Case Asc("1") To Asc("9") Case Asc("-") If InStr(1, Me.txt_length.Text, "-") > 0 Or Me.txt_length.SelStart > 0 Then KeyAscii = 0 End If Case Asc(".") If InStr(1, Me.txt_length.Text, ".") > 0 Then KeyAscii = 0 End If Case Else KeyAscii = 0 End Select End Sub Private Sub txt_studentNo_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) ' Restrict entry to txt_studentNo Select Case KeyAscii Case Asc("0") To Asc("9") Case Asc("-") If InStr(1, Me.txt_studentNo.Text, "-") > 0 Or Me.txt_studentNo.SelStart > 0 Then KeyAscii = 0 End If Case Asc(".") If InStr(1, Me.txt_studentNo.Text, ".") > 0 Then KeyAscii = 0 End If Case Else KeyAscii = 0 End Select End Sub 

您可以设置一个私人function,并从每个按键中调用它:

  Private Sub txt_noRooms_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) ' Restrict entry to txt_noRooms If bclearfield(CLng(KeyAscii), Me.txt_noRooms.Text, Me.txt_noRooms.selStart,"1") Then KeyAscii = 0 End Sub Private Sub txt_length_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) ' Restrict entry to txt_length If bclearfield(CLng(KeyAscii), Me.txt_length.Text, Me.txt_length.selStart,"1") Then KeyAscii = 0 End Sub Private Sub txt_studentNo_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) ' Restrict entry to txt_studentNo If bclearfield(CLng(KeyAscii), Me.txt_studentNo.Text, Me.txt_studentNo.selStart,"0") Then KeyAscii = 0 End Sub Private Function bClearField(KeyAscii As Long, sText As String, lSelStart As Long,sLowLimit as string) As boolean bClearField=false Select Case KeyAscii Case Asc(sLowLimit ) To Asc("9") Case Asc("-") If InStr(1, sText, "-") > 0 Or lSelStart > 0 Then bClearField=true End If Case Asc(".") If InStr(1, sText, ".") > 0 Then bClearField=true End If Case Else bClearField=true End Select End Function