In Excel 2013 (Office 15) a combination of a shortcut and a very simple userform (for formatting) is sometimes causing the Active Workbook to disappear and another workbook to show for no reason (only happens sometimes, often after just having changed activeworkbook). I am trying to keep the current workbook window in the foreground while the formatting userform is shown but without success.
Here is my code:
Sub AssignKeys()
Application.OnKey "^%,", "MakeBlue"
End Sub
Sub MakeBlue()
frmFormat.Show
End Sub
frmFormat is a very simple and small form that only has one textbox where a formatting code is entered. It does work to restore the previously active workbook after hiding the modal form using this code:
Private Declare PtrSafe Function SetForegroundWindow Lib "USER32" (ByVal hWnd As LongPtr) As LongPtr
Public Sub MyAppActive(Handle As Long)
Dim lngStatus As LongPtr
lngStatus = SetForegroundWindow(Handle)
End Sub
Private Sub tbShortcut_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If tbShortcut.Text <> "xn" Then
Dim mySel As Range
Dim myWb As workBook
Dim myWnd As Window
Set myWnd = ActiveWindow
Set mySel = Selection
Set myWb = ActiveWorkbook
Debug.Print mySel.Address
Me.Hide
'mySel.Parent.Parent.Activate
myWb.Activate
myWnd.Activate
MyAppActive myWnd.hWnd
end if
end sub
So once the form is hidden, the original workbook window is restored. But while the userform is shown, the other unwanted Workbook window is displayed. Would be very greatful for any hints. Thank you!
.Activate
? – Comintern