Running an Excel macro in a specific workbook is not performed from C #

I am trying to run a macro in an Excel workbook from C # using the standard Microsoft.Office.Interop.Excel library. In my scenario, the version of Excel can be either in 2010 or in 2013.

You can open several books for the same application object, each of which can have the same macro names, so I explicitly pass the name of the book

string macro = string.Format("{0}!{1}", workbook.Name, macroName);
Application.Run(macro);

Oddly enough, I get a COMException if there are hyphens in the title of the book:

Application.Run("My-Workbook!macro1")

But it works fine without a hyphen:

Application.Run("MyWorkbook!macro1")

Is it just me or is it weird? Can anyone think of a workaround?

+4
source share
1 answer

Wrap the name of the book in quotes.

string macro = string.Format("'{0}'!{1}", workbook.Name, macroName);
Application.Run(macro);
+4

Source: https://habr.com/ru/post/1583887/


All Articles