Skip to content Skip to sidebar Skip to footer

Can Office-JS Trigger A VBA Workbook Or Worksheet Event Procedure?

I'm trying to see if there is a way to do something in Office-JS that would trigger an event procedure to run in Excel VBA, but it looks like VBA events are disabled during the exe

Solution 1:

The change event does not run but the selectionchange event does, so you could use that to trigger your code: populate a specific cell and then select it

sheet.getRange("A999").values = 'Hello from Office-JS';
sheet.getRange("A999").select();

Sheet module:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Address(False, False) = "A999" Then
        MsgBox Target.Value
    End If
End Sub

EDIT: on review, the OP for the original question already worked most of this out...


Solution 2:

After some more testing, I managed to find that the Workbook_NewSheet event procedure of the workbook object gets triggered by creating a new worksheet with Office-Js:

var sheets = context.workbook.worksheets;
var sheet = sheets.add("NewSheet");
sheet.getRange("A1").values = "Hello from Office-JS";

So, it would be possible to have the following code in the ThisWorkbook Module to display the Message box in that context:

Private Sub Workbook_NewSheet(ByVal Sh As Object)
    If Sh.Name = "NewSheet" Then
        If Sh.Range("$A$1").Value2 <> vbNullString Then
            MsgBox Sh.Range("$A$1").Value2
        End If
    End If
End Sub

The nice thing here is that even if the Office-JS code writes to the sheet after creating it, the event in VBA only gets to run after the JavaScript code has finished meaning that the value in cell A1 will be changed in time for when the VBA code runs.


Post a Comment for "Can Office-JS Trigger A VBA Workbook Or Worksheet Event Procedure?"