How to Protect Macro in VBA

Iqra Hasnain Feb 15, 2024
  1. Protect Macro From Being Viewed in VBA
  2. Protect Macro From Being Executed in VBA
How to Protect Macro in VBA

We will introduce how to protect macro from being viewed and executed in VBA. We will also introduce different steps to set a password for our macro.

Protect Macro From Being Viewed in VBA

Protecting our data is very important; we never know how someone will use it. As we can protect workbooks and worksheets by simply putting a password to them, we can also secure a macro in Excel from being viewed.

First, we will add a command button on the desired worksheet.

Add a CommandButton in Worksheet

Then, we will create a simple macro we want to protect from viewing. As shown below, we will create a simple macro that will assign a value to a cell inside the sheet.

Private Sub CommandButton1_Click()
Range("D1").Value = "This is a protected cell"
End Sub

Output:

creating a macro to protect in VBA

Now we will select Tools from the menu bar in VBA. A list will pop up, then select VBAProject Properties.

When VBA project properties open, we will see the General and Protection tabs.

protect macro in VBA step 1

We must select the Protection tab and check the Lock project for viewing.

We have to enter the password twice to confirm it. And then, we have to select OK, as shown below.

protect macro in VBA step 2

Save the changes and close the Excel file, then open it again. A dialog box will pop up when we try to see the code in VBA.

To see a file in VBA, we have to enter the correct password.

box for password

We can still execute the code by clicking on the command button, but we can no longer view or edit the code unless we input the correct password.

Protect Macro From Being Executed in VBA

There are situations in which we only want to protect a macro from being executed in VBA. We can use the Application.InputBox as a password protection tool for this case.

When a user enters the correct word inside the box, it will execute the code. Otherwise, it will display an incorrect message and stop the code from executing.

Let’s go through an example in which we will try to put a value to a certain cell in Excel using VBA. As shown below, we will use the above method to protect the VBA code from executing.

Sub Pass()
Dim password As Variant
passcode = Application.InputBox("Enter Pass Code", "Password Protected")

Select Case passcode
    Case Is = False
    Case Is = "password"
        Range("B1").Value = "Code executed!"
    Case Else
        MsgBox "Incorrect Pass Code"
End Select
End Sub

Output:

protection from executing in VBA

In this way, we can easily protect our macro from viewing and executing with the help of VBA.