How to restrict sheet visibility to certain users using VBA?

Restricting sheet visibility to certain users using VBA involves a combination of using Excel’s built-in features and VBA programming. You would typically want to hide the sheet upon opening the workbook and only make it visible if the user has the proper credentials. Here is a general guide on how you can achieve this:

Prerequisites:

  • User Identification: You need a way to identify users. This could be their login usernames or some sort of password prompt.
  • Security Note: Understand that VBA-based security should not be considered foolproof. Savvy users can bypass restrictions if they disable macros or access the VBA editor.

Steps:

Step 1: Identify Users

Decide the method of user identification, either by using the system username or password input.

Step 2: Use VBA to Control Sheet Visibility

Here is a basic example using VBA to make a sheet visible based on the username:

Sub CheckUserAccess()
    Dim userName As String
    ' Get the system's username
    userName = Environ("Username")
    
    ' Assume "Sheet1" is the sheet you want to restrict
    ' Check the username and set sheet visibility accordingly
    If userName = "allowedUser1" Or userName = "allowedUser2" Then
        ' Make the sheet visible
        ThisWorkbook.Sheets("Sheet1").Visible = xlSheetVisible
    Else
        ' Hide the sheet
        ThisWorkbook.Sheets("Sheet1").Visible = xlSheetVeryHidden
    End If
End Sub

Private Sub Workbook_Open()
    CheckUserAccess
End Sub
  • Open the VBA Editor:
    • Press `ALT + F11` to open the VBA editor in Excel.
  • Insert a Module:
    • Right-click anywhere in the left pane where your workbook is listed (e.g., `VBAProject (YourWorkbookName.xlsx)`) and select `Insert > Module`.
  • Add the Following VBA Code:

Step 3: Ensure Macro Runs on Opening

To ensure the macro runs automatically when the workbook is opened, place the `CheckUserAccess` call inside the `ThisWorkbook` object:

  • In the VBA editor, find `ThisWorkbook` under your project.
  • Double-click to open it and add the `Workbook_Open` subroutine as shown above which calls `CheckUserAccess`.

Step 4: Password Prompt (Optional)

If you prefer using a password prompt for access, replace the user identification part with an `InputBox` prompt and password check in `CheckUserAccess`.

Caveats:

  • Security Risks: VBA does not offer robust security, as users can access or disable macros.
  • VeryHidden Property: When a sheet is set to `xlSheetVeryHidden`, it cannot be unhidden via the Excel interface, only through VBA.

This method will restrict sheet visibility, but remember it’s primarily suitable for deterrents against average users, rather than high-security requirements. For more secure solutions, consider implementing protection at the file or network level.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project