Reputation: 941
I'm developing an excel add-in (office 2013).
I would like to overwrite an Excel keyboard shortcut.
For instance, ctrl+e must now center the text in a cell.
Where do I start? I can't find it in the interop documentation.
Upvotes: 3
Views: 2442
Reputation:
Well, there is no pure C# way to assign a shortcut to a command but I think I have just figured out a workaround.
In Excel, you can assign a shortcut to a macro. This obviously means you need to have a macro in your workbook. If you are working with interop you can create a macro programmatically and assign a shortcut to it.
Create an addModule()
function which creates a standard coding module programmatically and writes code to it. Then use Application.OnKey()
to assign a shortcut to that macro.
your addModule()
void addModule()
{
VBProject vbProj = Globals.ThisWorkbook.VBProject as VBProject;
VBComponent vbComp =
vbProj.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
vbComp.CodeModule.DeleteLines(1, vbComp.CodeModule.CountOfLines);
string code = "Public Sub CentreText() \n" +
" activeCell.HorizontalAlignment = xlCenter \n" +
"End Sub";
vbComp.CodeModule.AddFromString(code);
}
The code
string is a pure VBA macro which centres activeCell
's text horizontally.
Then anywhere in your executable code:
addModule();
Worksheet ws = Globals.ThisWorkbook.ActiveSheet as Worksheet;
Workbook wb = ws.Parent as Workbook;
Microsoft.Office.Interop.Excel.Application app =
wb.Parent as Microsoft.Office.Interop.Excel.Application;
app.OnKey("^e", "CentreText");
Upvotes: 5