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

How to use workbook activate application class event with automation

我需要工作簿激活应用程序 class 事件代码,它会在激活工作簿时最小化 "Workbook Window"。

因此,只要 C:\Book1.xlsx 被激活,然后最小化 "Workbook Window"。

以下代码仅供测试开始;

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

关注link可能会支持你;

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

首先要做的是将 xlApp 的声明移动到 class 级别并声明 WithEvents:

Private WithEvents xlApp As New Excel.Application

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

Occurs when any workbook window is activated.

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

WindowResize

Occurs when any workbook window is resized.

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