VBA用代码设置文本框焦点的2种方法

2017-09-18 14:24:00
zstmtony
原创
185

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