VBA macros in Excel spreadsheets are used to automate different operations programmatically. For example, you can program a task that is to be done repeatedly, generate graphs using code, etc. However, the protection of VBA macros from unauthorized users is an important aspect. In order to handle this issue, this article covers how to protect VBA macros in Excel spreadsheets programmatically using C#.
C# API to Protect Excel VBA Macros
In order to protect the Excel VBA macros, we will use Aspose.Cells for .NET API. It is a powerful spreadsheet manipulation API that lets you implement Excel automation from within your .NET applications. In addition, the API allows you to work with VBA macros in Excel files seamlessly. You can either download the API’s DLL or install it using NuGet.
PM> Install-Package Aspose.Cells
Protect Excel VBA Macros using C#
VBA macros in Excel spreadsheets are encapsulated by VBA projects where each VBA project may contain one or more VBA macros (or modules). Therefore, to protect the VBA macros, you simply need to apply protection on the VBA project.
The following are the steps of how to protect an Excel VBA project.
- Load the Excel file using Workbook class.
- Access the VBA project into a VbaProject object using Workbook.VbaProject property.
- Protect the VBA project with a password using VbaProject.Protect(bool, string) method.
- Save the updated Excel file using Workbook.Save(String) method.
The following code sample shows how to protect the Excel VBA project using C#.
MS Excel shows the following message when you try to view the password-protected VBA project.
Get a Free API License
You can get a free temporary license in order to use the API without evaluation limitations.
In this article, you have learned how to protect VBA macros in Excel files using C#. The step-by-step guide along with API references and code sample have shown how to apply a password to a VBA project. You can explore more about Aspose.Cells for .NET using the documentation. In case you would have any queries, feel free to let us know via our forum.