2012-10-10 66 views
0

我已經寫了三個不同的私人小組功能,所有這些都做同樣的事情私人小組txt_noRooms_KeyPress私人小組txt_length_KeyPress確保用戶可以將值1只輸入到9到引用的文本字段中,而Private Sub txt_studentNo_KeyPress允許用戶在引用的文本字段中鍵入值0到9。在Excel中合併私人小組功能VBA

有什麼辦法可以合併這三個函數,並讓它們仍然支持引用的單元格並保持相同的條件?我想這樣做是爲了使代碼更高效。

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 

回答

3

您可以設置一個專用功能,並且從每個按鍵調用它:

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 
+0

我似乎無法輸入任何東西到字段現在 – methuselah

+0

你嘗試設置一個斷點('F9')在其中一個按鍵子集中,並進入代碼('F8')來查看問題是什麼? – nutsch

+0

我已經更改了函數返回的var類型。不知道這是否有幫助。 – nutsch