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

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

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
分享