Unable to click the MS Forms button that is on Excel Sheet
Hi
There is one excel sheet where some values are in cells and some controls present on sheet like button, checkbox, datafilter button. I want to click the button that is on excel sheet from another application may be C# based code application. I tried but unable to click on button. I can access the button, can change the caption of button but unable to click on that button. Some one can help me out from this problem. This button can be added by right clicking the toolbar of excel sheet and select Control Toolbox and grag the Command button control on sheet.
Regards
Sunil Kumar Sinha
Are you obtaining the button as an AutomationElement, using UIAutomation? If so, you should be able to get the Invoke control pattern and then call the Invoke method.
However, be aware that support for Excel in UI Automation is currently limited.
Hi All
I found one solution that will click on Excel button(MS Form CommandButton). Below is the code in C# that will fire click event of an excel button
using
System;using
System.Collections.Generic;using
System.Text;using
Excel = Microsoft.Office.Interop.Excel;using
VBIDE = Microsoft.Vbe.Interop;using
System.Diagnostics;using
System.Runtime.InteropServices;using
System.Reflection;using
System.Threading;public
static bool ClickExcelButton(Excel.Worksheet excelWorksheet, string buttonName){
Excel.
OLEObject button; bool status = false;try{
excelWorksheet.Activate();
button = (Excel.
OLEObject)excelWorksheet.OLEObjects(buttonName); if (button.Visible == true){
button.Activate();
button.Application.SendKeys(
" ", true); status =
true;}
if (button != null){
Marshal.ReleaseComObject(button);button =
null;}
return status;}
catch (Exception ex){
Console.WriteLine("Exception occured in ClickExcelButton: " + ex.Message);status =
false;return status;}
}
Thanks & Regards
Sunil Kumar Sinha
Sunil, that is a good one.
In my case, I dynamically create the button in excel sheet, but I am not sure how to link it to a C# method as a handler for the click of that button. Any ideas?
Below is the source code to trap the click event of Excel button.
public
static object FindControl(string name, Excel.Worksheet sheet)
{
Excel.OLEObject theObject;
try
{
theObject = (Excel.
OLEObject)sheet.OLEObjects(name);return theObject.Object;}
catch (Exception ex){
// Returns null if the control is not found.Console.WriteLine(ex.Message);return null;}
}
void MainFunction()
{
string
buttonName = "cmdImportResources";MSForms.
CommandButton cmdAddResource = (MSForms.CommandButton)FindControl(buttonName, wsBudget);cmdAddResource.Caption =
"Changed";if (cmdAddResource != null){
cmdAddResource.Click +=
new Microsoft.Vbe.Interop.Forms.CommandButtonEvents_ClickEventHandler(cmdAddResource_Click);}
}
static
void cmdAddResource_Click(){
Console.WriteLine("Button Clicked"); }
Sunil Sinha
esunilsinha@hotmail.com
sunilsinha77@gmail.com