Wrong Excel Window in Focus after Workbook_Open

♀尐吖头ヾ 提交于 2019-12-03 14:53:11

When Comintern's code did not change the behavior, I focused on whether this was a timing issue, with IndexReturns not having an active window until after the code Activated the other workbook. And code to adjust for this seems to have solved the problem.

I added a loop to test for the presence of a Window of IndexReturns before executing the AppActivate method.

Set wb = wbs.Open(IndexReturns)

Do
    DoEvents
Loop Until wb.Windows.Count > 0

AppActivate sTitle

For good measure, I also made that window invisible, as I have no need to access it for other than debugging purposes:

wb.Windows(1).Visible = False

This seems to have solved the problem brought about by Excel 2016 opening files differently compared with 2007.

I obviously can't test in your environment, but I'd try bypassing whatever Excel is doing and using a call to BringWindowToTop or SetForegroundWindow instead of AppActivate:

#If VBA7 Then
    Public Declare PtrSafe Function BringWindowToTop Lib "user32" (ByVal _
             hwnd As LongPtr) As Boolean
    Public Declare PtrSafe Function SetForegroundWindow Lib "user32" (ByVal _
             hwnd As LongPtr) As Boolean
    Public Declare PtrSafe Function FindWindow Lib "user32" Alias _
            "FindWindowA" (ByVal lpClassName As Any, ByVal lpWindowName _
            As Any) As LongPtr
#Else
    Public Declare Function BringWindowToTop Lib "user32" (ByVal _
             hwnd As Long) As Boolean
    Public Declare Function SetForegroundWindow Lib "user32" (ByVal _
             hwnd As Long) As Boolean
    Public Declare Function FindWindow Lib "user32" Alias _
            "FindWindowA" (ByVal lpClassName As Any, ByVal lpWindowName _
            As Any) As Long
#End If

Then...

    Dim hwnd As Long
    hwnd = FindWindow(vbEmpty, sTitle)    'sTitle contains title of thisworkbook
    BringWindowToTop hwnd     
    '...or...
    SetForegroundWindow hwnd
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!