office交流網--QQ交流群號

Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

VBA用代碼設置文本框焦點的2種方法

2017-09-18 14:24:00
zstmtony
原創
1842

vba 如何控制 textbox控件 在 按回車鍵后 焦點轉移,正常是設置2個文本框控件的Tab鍵順序。

但有否其它辦法來實現 有兩個 textbox 控件  在 第一個 textbox 輸入完了后 按 回車 (enter ) 焦點轉移到 第二個 textbox


實現辦法一(使用Sendkeys 用回車鍵來模擬TAB鍵):



Private Sub Text1_KeyPress(KeyAscii As Integer)

    If KeyAscii = 13 Then '13是回車鍵的Ascii碼

        KeyAscii = 0

        SendKeys "{TAB}"

    End If

End Sub 

Private Sub Text2_KeyPress(KeyAscii As Integer)

    If KeyAscii = 13 Then

        KeyAscii = 0

        SendKeys "{TAB}"

    End If

End Sub


實現辦法二(使用API來實現):



Option Explicit

Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Private Const WM_KEYUP = &H101

Private Const WM_KEYDOWN = &H100

Private Const VK_TAB = &H9

Private Sub Text1_KeyPress(KeyAscii As Integer)

    If KeyAscii = 13 Then

        PostMessage Text1.hwnd, WM_KEYDOWN, VK_TAB, 0

        Sleep 100

        PostMessage Text1.hwnd, WM_KEYUP, VK_TAB, 0

    End If

End Sub


Private Sub Text2_KeyPress(KeyAscii As Integer)

    If KeyAscii = 13 Then

        PostMessage Text2.hwnd, WM_KEYDOWN, VK_TAB, 0

        Sleep 100

        PostMessage Text2.hwnd, WM_KEYUP, VK_TAB, 0

    End If

End Sub
分享
北京十一选五基本走势