返回列表 上一主題 發帖

[發問] 請教TextBox輸入錯誤如何回到原位置

[發問] 請教TextBox輸入錯誤如何回到原位置

請教各位先進:
TextBox1輸入錯誤跳出MsgBox提示視窗後要如何回到TextBox1重新輸入
            MsgBox "輸入錯誤"
            TextBox1 = ""
            TextBox1.SetFocus
使用SetFocus失敗焦點會跳到TextBox2
使用Application.SendKeys "{up}"經常會造成NumLook關閉
  1. Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
  2.     If KeyCode = 13 And TextBox1 > "" Then
  3.         Dim Rng As Range
  4.         Dim ax As Variant
  5.         Dim bx As String
  6.         Set Rng = Sheets("data").[K1:L24]
  7.         bx = TextBox1.Text
  8.         ax = Application.VLookup(bx, Rng, 2, 0)
  9.         If Not IsError(ax) Then
  10.             Label4 = ax
  11.         Else
  12.             MsgBox "輸入錯誤"
  13.             TextBox1 = ""
  14.             Application.SendKeys "{up}"
  15.             Exit Sub
  16.         End If
  17.     End If
  18. End Sub
複製代碼

暫時先用全域變數來解決
  1. Dim bCancel As Boolean

  2. Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
  3. Cancel = bCancel
  4. bCancel = False
  5. End Sub
複製代碼

TOP

回復 2# koo

Cancel = True 即可取消Exit動作, 讓駐點留在原位,
但加個Msgbox後, 駐點整個消失不見了!
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox1 = 1 Then
 Cancel = True
 TextBox1 = ""
 MsgBox "ERROR" '消除此行再試看看
Else
 MsgBox "通過"
End If
End Sub
 
但題主用的是KeyDown事件,Enter後駐點已移位,回不了頭的!
 

TOP

回復 3# 准提部林
Cancel = True 即可取消Exit動作, 讓駐點留在原位
同理
ByVal KeyCode As MSForms.ReturnInteger
  1. Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
  2.     If KeyCode = 13 And TextBox1 > "" Then
  3.         Dim Rng As Range
  4.         Dim ax As Variant
  5.         Dim bx As String
  6.         Set Rng = Sheets("data").[K1:L24]
  7.         bx = TextBox1.Text
  8.         ax = Application.VLookup(bx, Rng, 2, 0)
  9.         If Not IsError(ax) Then
  10.             Label4 = ax
  11.         Else
  12.             MsgBox "輸入錯誤"
  13.             'TextBox1 = ""
  14.             KeyCode = True
  15.             TextBox1.SelStart = 0
  16.             TextBox1.SelLength = Len(TextBox1)
  17.         End If
  18.     End If
  19. End Sub
複製代碼
感恩的心......(在麻辣家族討論區.用心學習會有進步的)
但資源無限,後援有限,  一天1元的贊助,人人有能力.

TOP

回復 4# GBKEE


好個 KeyCode = True, 多收一招!
不過 MSGBOX 後, 駐點還是看不到, 不知是否版本問題(XP + 2000)?

TOP

回復 5# 准提部林
沒有2000可了解
  1. TextBox1.SelStart = 0
  2. TextBox1.SelLength = Len(TextBox1)
複製代碼
試試不MsgBox, 這段程式碼可用嗎?
感恩的心......(在麻辣家族討論區.用心學習會有進步的)
但資源無限,後援有限,  一天1元的贊助,人人有能力.

TOP

回復 6# GBKEE

加那兩行也是沒用, MSGBOX後, 駐點完全消失~~
為了克服這個問題, 以前都在Form下方加個Label做為說明提示及警告用(多個beep音效),
也乾脆輸入完成後, 在登錄按鈕時再執行前置檢查, 完全正確再後續工作,
有時在工作表設計成類輸入表單, 反而更好用~~

TOP

謝謝2位大大解說
使用KeyCode = True可以正常執行W7+2013
感謝

            MsgBox "輸入錯誤"
            KeyCode = True
            TextBox1.SelStart = 0
            TextBox1.SelLength = Len(TextBox1)

TOP

        靜思自在 : 成功是優點的發揮,失敗是缺點的累積。
返回列表 上一主題