The following is a piece of code to subscribe and handle Excel events
1 Clear-Host 2 $excel = New-Object -ComObject Excel.Application 3 $wb = $excel.Workbooks.Add() 4 $sht = $wb.Worksheets[1] 5 Register-ObjectEvent -InputObject $excel -EventName SheetChange -SourceIdentifier Excel.SheetChange -Action { 6 Write-Host '$Event自动变量拥有的属性:' 7 $Event | fl | Out-Host 8 Write-Host [1] ('ComputerName: {0}' -f $Event.ComputerName) 9 Write-Host [2] $Event .RunspaceId 10 Write-Host [3] $Event .EventIdentifier 11 Write-Host [4] $Event .Sender 12 Write-Host [5] ( $Event .SourceEventArgs -eq $null ) 13 #No output, it can be seen that although this member exists in the property of $Event, it is inaccessible. Please use $Args instead of 14 Write-Host [6] ( $Event .SourceArgs -eq $null ) 15 Write-Host [ 7] $Event .SourceIdentifier 16 Write-Host [8] $Event .TimeGenerated 17 Write-Host [9] $Event .MessageData 18 Write-Host ('-' * 10 ) 19 $Target = $Args [1 ] 20 Write-Host [1] $Target .Address() 21 #Read the cell's When setting the value, be sure to use Value2, the original Value property is an object, for some reason 22 write-host [2] $Target .Value2 23 Write-Host [3] $Args .Count 24 Write-Host [4] $Args [ 0 ].Name 25 # turned out to be $false, I don't know why 26 Write-Host [5] ( $Args [0] -eq $sht ) 27 #It should return $true, but there is no output, I don't know why 28 Write-Host [6] ( $Target -eq $sht .Range('A1')) 29 Write-Host [7] $Sender . Name 30 Write-Host [8] ( $Sender -eq $excel ) 31 } -MessageData " SheetChange Event Happened! " | Out- Null 32 $sht .Cells(1, 1).Value = 'hello' 33 #Wait for the event Response 34 Start-Sleep 2 35 $wb .Close( $false ) 36 $excel.Quit() 37 Unregister-Event Excel.SheetChange
Its execution result is as follows: