以编程方式在Excel中隐藏活动工作簿

时间:2012-07-06 00:42:08

标签: excel vba excel-vba screen

我正在开发一个基于工作簿的VBA项目。该代码打开一个新的工作簿并调用外部API,该API在这个新工作簿的多个工作表中下载并插入一堆数据。我停用了屏幕更新(Application.Screenupdating = False),因此最初屏幕会一直关注原始工作簿,而API会在后台下载其他工作簿上的数据。但是,一旦API插入数据,屏幕就会切换到新工作簿。我怎样才能防止这种情况发生?谢谢!

3 个答案:

答案 0 :(得分:20)

可以使用

隐藏活动工作簿
ActiveWorkbook.Windows(1).Visible = False

如果相关工作簿不是活动工具簿,则可能需要将ActiveWorkbook替换为适当的引用;如果工作簿具有多个窗口,则可能需要添加For i = 1 To ActiveWorkbook.Windows.Count之类的循环。

答案 1 :(得分:5)

您可以尝试使用ShowWindow API函数:

Public Declare Function ShowWindow Lib "user32.dll" _
    (ByVal HWND As Long, ByVal nCmdShow As Long) As Long

Const SW_HIDE as Long = 0
Const SW_SHOW as Long = 5

ShowWindow otherWorkbookApplication.Hwnd, SW_HIDE

'Your code here

ShowWindow otherWorkbookApplication.Hwnd, SW_SHOW

或者,LockWindowUpdate API函数(感谢Chip Pearson,http://www.cpearson.com/excel/vbe.aspx):

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
    (ByVal ClassName As String, ByVal WindowName As String) As Long

Private Declare Function LockWindowUpdate Lib "user32" _
    (ByVal hWndLock As Long) As Long


Sub EliminateScreenFlicker()
    Dim VBEHwnd As Long

    On Error GoTo ErrH:

    Application.VBE.MainWindow.Visible = False

    VBEHwnd = FindWindow("wndclass_desked_gsk", _
        Application.VBE.MainWindow.Caption)

    If VBEHwnd Then
        LockWindowUpdate VBEHwnd
    End If

    '''''''''''''''''''''''''
    ' your code here
    '''''''''''''''''''''''''

    Application.VBE.MainWindow.Visible = False
ErrH:
    LockWindowUpdate 0&
End Sub

答案 2 :(得分:3)

您需要保存并关闭目标工作簿,或者在重新启用screenupdating之前选择原始工作簿。