如何使用工作簿激活自动化应用程序类事件

时间:2017-03-28 03:38:24

标签: excel vb.net excel-interop

我需要工作簿激活应用程序类事件代码,以便在激活工作簿时最小化“工作簿窗口”。

因此,只要激活C:\Book1.xlsx,就会最小化“工作簿窗口”。

以下代码仅用于测试开始;

Imports Microsoft.Office.Interop

Public Class Form1

Public WithEvents wb1 As Excel.Workbook

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    Dim xlApp As New Excel.Application
    xlApp.Visible = True

    Threading.Thread.Sleep(10000)

    Dim wb1 As Excel.Workbook
    wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")

    Threading.Thread.Sleep(100000000)
End Sub

End Class

以下链接可能会为您提供支持;

https://support.microsoft.com/en-us/help/822750/how-to-handle-events-for-excel-by-using-visual-basic-.net

1 个答案:

答案 0 :(得分:0)

要做的第一件事是将xlApp的声明移到班级并声明WithEvents

Private WithEvents xlApp As New Excel.Application

现在我们可以使用Excel.Application附带的事件,特别是WindowActivate

  

在激活任何工作簿窗口时发生。

Private Sub xlApp_WindowActivate(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowActivate
    xlApp.WindowState = Excel.XlWindowState.xlMinimized
End Sub

WindowResize

  

在调整任何工作簿窗口大小时发生。

Private Sub xlApp_WindowResize(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowResize
    xlApp.WindowState = Excel.XlWindowState.xlMinimized
End Sub

如您所见,在这些处理程序中,我将WindowState属性设置为xlMinimized。这意味着每当我尝试调出Workbook时,它就会再次被最小化。

完整的代码看起来与此类似:

Public Class Form1

    Private WithEvents xlApp As New Excel.Application

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

        xlApp.Visible = True

        Dim wb1 As Excel.Workbook
        wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")

    End Sub

    Private Sub xlApp_WindowActivate(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowActivate
        xlApp.WindowState = Excel.XlWindowState.xlMinimized
    End Sub

    Private Sub xlApp_WindowResize(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowResize
        xlApp.WindowState = Excel.XlWindowState.xlMinimized
    End Sub

End Class