I am trying to execute the following code
const string excelFile = @"C:\test.xls";
var excelApplication = new ExcelInterop.Application { Visible = true };
var targetExcelFile = excelApplication.Workbooks.Open(excelFile,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
var newStandardModule = targetExcelFile.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
var codeModule = newStandardModule.CodeModule;
// add vba code to module
var lineNum = codeModule.CountOfLines + 1;
var macroName = "test";
var codeText = " Sub " + macroName + "()" + "\r\n";
codeText += " Dim xsheet As Worksheet" + "\r\n";
codeText += "For Each xsheet In ThisWorkbook.Worksheets" + "\r\n";
codeText += " xsheet.Select" + "\r\n";
codeText += "With xsheet.UsedRange" + "\r\n";
codeText += " .Value = .Value" + "\r\n";
codeText += " End With" + "\r\n";
codeText += "Next xsheet " + "\r\n";
codeText += "End Sub";
codeModule.InsertLines(lineNum, codeText);
targetExcelFile.Save();
// run the macro
var macro = string.Format("{0}!{1}.{2}", targetExcelFile.Name, newStandardModule.Name, macroName);
excelApplication.Run(macro,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing
);
excelApplication.Quit();
I always got the following error
"Can not run the macro xx. may not be available in this workbook or all macros are disabled."
How to resolve the error? Any suggestions ?
macro
inexcelApplication.Run(macro, Type.Missing...
- Siddharth RoutRun
to use. - Rory