How to check whether an Excel document contains macro?
25 May 20232 minutes to read
You can check whether the Excel document contains macro using HasMacros property of IWorkbook. The value true indicates that the Excel document has a Vba project.
The following code illustrate how to check whether an Excel document contains macro using XlsIO.
using (ExcelEngine excelEngine = new ExcelEngine())
{
//Instantiate the excel application object.
IApplication application = excelEngine.Excel;
//Opening form module existing workbook
FileStream input = new FileStream("Test.xls", FileMode.Open, FileAccess.ReadWrite);
IWorkbook workbook = application.Workbooks.Open(input);
IWorksheet sheet = workbook.Worksheets[0];
//Check macro exist
bool IsMacroEnabled = workbook.HasMacros;
// Save the workbook
FileStream output = new FileStream("Output.xls", FileMode.Create, FileAccess.ReadWrite);
workbook.SaveAs(output);
input.Close();
output.Close();
}
using (ExcelEngine excelEngine = new ExcelEngine())
{
// Instantiate the excel application object.
IApplication application = excelEngine.Excel;
// Opening a workbook
IWorkbook workbook = application.Workbooks.Open("Test.xls");
IWorksheet sheet = workbook.Worksheets[0];
//Check macro exist
bool IsMacroEnabled = workbook.HasMacros;
//Save the workbook
workbook.SaveAs("Output.xls");
}
Using excelEngine As ExcelEngine = New ExcelEngine()
'Instantiate the excel application object.
Dim application As IApplication = excelEngine.Excel
'Opening a Workbook
Dim workbook As IWorkbook = application.Workbooks.Open("Test.xls")
Dim sheet As IWorksheet = workbook.Worksheets(0)
'Check macro exist
Dim IsMacroEnabled As Boolean = workbook.HasMacros
‘Save the workbook
workbook.SaveAs("Output.xls")
End Using