Record Excel Macro Programatically - C#

Prateek Gupta 1 Reputation point
2021-03-02T09:39:58.083+00:00

I am trying to record macros in excel application via C# WPF application. After running the application, while moving focus to excel application, the macro should start, and while switching to some other application, the macro recording should stop.

I have tried implementing it using

focusHandler = new AutomationFocusChangedEventHandler(OnFocusChanged);
Automation.AddAutomationFocusChangedEventHandler(focusHandler);

This helps in detecting focus change on application. Then after filtering application type as excel, I am using the following to start macro in excel using interop:

var macroStartButton = 
excelApp.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, 184);
macroStartButton.Execute();

Then again when focus changes to other application, using the following to stop macro recording:

macroStopButton = 
 excelApp.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, 2186);
 macroStopButton.Execute();

The above approach is working intermittently. Can someone suggest a better approach or changes to current approach.

Developer technologies Windows Presentation Foundation
Developer technologies C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.