0

I am trying to embed an excel workbook into WPF application. I have used the Microsoft.Office.Interop.Excel for achieving this, It works and opens the excel workbook in WPF application.

Problem: When I try to run the macros in VBA the workbook gives away the focus (deactivates the worksheet) and in order to work further I need to double click and activate the worksheet first which is not user friendly and usable for the customers.

Is there any way to overcome this issue or listen to the events from VBA in WPF application to activate the worksheet automatically.

setting AutomationSecurity in Excel to msoAutomationSecurityLow allows running the VBA in excel and causes this behavior.

Microsoft.Office.Interop.Excel excelApplication = new Microsoft.Office.Interop.Excel();
excelApplication.Visible = true;

// this is to enable the VBA, disabling the VBA works fine.
excelApplication.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityLow;

Microsoft.Office.Interop.Workbooks workbooks = excelApplication.Workbooks;
Microsoft.Office.Interop.Workbook workbook = workbooks.Open("excel file path");

//setting the parent of excel to WPF window.
**SetParent(excelHandle, parentWindowHandle);**

Expectation: Run the excel workbook same as running standalone application in WPF application.

  • If your macros rely on the Active sheet, you should rework your macros. – FunThomas Aug 14 '23 at 14:32
  • I do not have any Active Sheet in macros, just a debug message Debug.Print "Worksheet selection change" one important thing is I am embedded the excel app in WPF window, if it run as standalone it works fine upon setting the parent of excel breaks the workflow. – Ganpat Gutte Aug 14 '23 at 19:57
  • It might be worth considering creating an AddIn using Visual Studio Tools for Office (VSTO). It uses Windows Forms for the Addin but you can use a ElementHost to populate the entire Winforms Control. Its worth a look : https://learn.microsoft.com/en-us/visualstudio/vsto/walkthrough-creating-your-first-vsto-add-in-for-excel?view=vs-2022&tabs=csharp – Dragan Radovac Aug 17 '23 at 00:53
  • @DraganRadovac, well my requirement is opposite, It's not hosting windows form control into excel but the other way around hosting an excel with it's full capability inside windows application. – Ganpat Gutte Aug 18 '23 at 02:36

0 Answers0