Workbook_Open之后,错误的Excel窗口焦点
我最近升级到Office 365 / Excel 2016导致了一些不必要的行为更改。 工作簿(“组合鉴赏”)包含Workbook_open过程,该过程检查Workbook(“Index Returns”)是否打开; 如果不是,则会打开该工作簿。
使用Excel 2007, Index Returns
将在后台打开,并保持在那里,这是所需的行为。 这将是“在窗口中”,可以在同一个Excel窗口中使用“ View
function区的“ Window
选项卡上的“ Arrange All
选项View
。
使用Excel 2016,如果它通过Workbook_Open过程打开,则Index Returns
将在其自己的Excel窗口Index Returns
打开,然后放在前面。 (不能再在与Portfolio Appreciation
相同的Excel窗口中查看)。
Index Returns
在前面的事实是问题。
我试过select和取消select忽略使用DDE的其他应用程序; 我已经尝试了AppActivate
方法(如下面的代码所示),并使用MsgBox
validation参数是否与相关的标题栏匹配。
不知道下一步该去哪里。 build议感激。
另外: Index Returns
包含macros或连接。 Portfolio Appreciation
包含除Workbook_Open
之外的macros,并且在打开时(查询下载一些股票指数的东西)有一个刷新的Web查询。
Option Explicit Private Sub Workbook_Open() Dim wbs As Workbooks, wb As Workbook Dim IndexReturns As String Dim re As RegExp Const sPat As String = "(^.*\\DATA\\).*" Const sRepl As String = "$1EHC\Investment Committee\indexreturns.xlsb" Dim sTitle As String sTitle = Application.Caption Set wbs = Application.Workbooks Set re = New RegExp With re .Pattern = sPat .Global = True .IgnoreCase = True End With IndexReturns = re.Replace(ThisWorkbook.FullName, sRepl) For Each wb In wbs If wb.FullName = IndexReturns Then Exit Sub Next wb Application.ScreenUpdating = False wbs.Open (IndexReturns) Set re = Nothing AppActivate sTitle 'sTitle contains title of thisworkbook 'The below doesn't work either 'AppActivate ThisWorkbook.Application.Caption Application.ScreenUpdating = True End Sub
当共同国际的代码没有改变行为,我专注于这是否是一个时间问题,与IndexReturns
没有一个活动窗口,直到代码激活其他工作簿之后。 而调整这个代码似乎已经解决了这个问题。
在执行AppActivate
方法之前,我添加了一个循环来testingIndexReturns
窗口的存在。
Set wb = wbs.Open(IndexReturns) Do DoEvents Loop Until wb.Windows.Count > 0 AppActivate sTitle
为了更好的衡量,我还将这个窗口隐藏起来,因为除了debugging之外,我不需要访问它:
wb.Windows(1).Visible = False
与2007年相比,这似乎解决了Excel 2016打开文件带来的问题。
我显然不能在你的环境中testing,但我会尝试绕过Excel正在做的事情,并使用调用BringWindowToTop或SetForegroundWindow而不是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
然后…
Dim hwnd As Long hwnd = FindWindow(vbEmpty, sTitle) 'sTitle contains title of thisworkbook BringWindowToTop hwnd '...or... SetForegroundWindow hwnd