Restrict Workbook to Specific Users Only in Excel VBA

Updated on October 1, 2018

Quick Overview

Excel is a commonly used application for sharing information around the workplace, with networked storage almost being a certain in all workplaces, some information may need to be kept from wondering eyes. Using the below guide, you'll be able to create a workbook that will automatically check the windows user that is logged in and allow / disallow access to the workbook.

This has been tested on Excel 2014 and later and Windows 10. Previous versions should work, but may not.

Step 1 - Accessing VBA And Opening The Workbook Module

VBA can be accessed in one of two ways:

  1. Simply press ALT + F11
  2. Head to the Options and select "View Developer Tab" then click Visual Basic (2007 Onwards)

When the editor opens, you'll be presented with a grey window with a project manager down the left hand side.

Project Manager - This is where you move between your workbook sheets, forms and modules to view and edit code.

Double click on "ThisWorkbook", a window will open on the right hand side and you are now ready to add some VBA to the workbook

Step 2 - Configure Code To Run On Workbook Open

The code below will execute when the workbook is opened, providing Macros are enabled for the workbook

Private Sub Workbook_Open()

End  Sub

All of your code for this guide will be placed between these two lines. When the workbook is opened, the code between theses lines will be executed

Step 3 - Get The Currently Logged In User

Use the following code to obtain the current user that is logged in. Remember to place this code between the Private Sub and End Sub lines

Dim user As String

user = Application.UserName

Step 4 - Define The Users That Can Access The Workbook

Here's where you specify exactly which users can open the workbook. We'll use an Array here as it makes it particularly easy to loop through the array and check the names

Add the following code ABOVE "User = Application.Username"

Dim users(5) As String

users(0) = "SomeUser"
users(1) = "SomeUser"
users(2) = "SomeUser"
users(3) = "SomeUser"
users(4) = "SomeUser"

Replace "SomeUser" with usernames that are granted access to the workbook. You can add more users by simply changing the number in "Dim users(x)" and adding the new user to the end of the list.

Make sure you remember that the Dim users(x) declaration is the number of elements in the array, not the last number. It will always be +1 higher than the last element you index as indexing starts at 0

Step 5 - Loop Through Array And Test Access

Now we'll loop through the array that was just created and test each element to see if the user in the array matches the user that is logged in.

Use the following code

Dim access As Boolean
Dim i As Integer

access = False

For i = 0 To 4
    If users(i) = user Then
        access = True
        Exit For
    End If

The above code first declares the new variables being used (access & i) and then sets access as false, the FOR statement then uses "i" to keep track of how many loops have been completed and loops through the users array by using users(i)

If the user in the array matches the user logged in (users(i) = user) then set access to TRUE and exit the for loop early.

If no user match is found, the access will still be set as false from before the loop was iterated.

Step 6 - Display A Message And Force Close The Workbook

If your user does not have access, we want to disallow them to proceed any further

If access = False Then
    MsgBox ("Sorry, the user """ & user & """ does not have the correct access rights to view this workbook")
End If

The above image will be displayed if the user does not match any of the names in the array we made earlier

And that's it!

Full Code Example

Just want to grab the code and get it working? Here's the complete code:

Private Sub Workbook_Open()
Dim user As String
Dim users(5) As String

users(0) = "SomeUser"
users(1) = "SomeUser"
users(2) = "SomeUser"
users(3) = "SomeUser"
users(4) = "SomeUser"

user = Application.UserName

Dim access As Boolean
Dim i As Integer

access = False

For i = 0 To 4
    If users(i) = user Then
        access = True
        Exit For
    End If

If access = False Then
    MsgBox ("Sorry, the user """ & "Liam" & """ does not have the correct access rights to view this workbook")
End If

End Sub


Dont forget to change the number of loops if you change the number of users or some will get missed or an error will occur!

It's a good idea to also create a blank sheet to open the workbook onto, to stop details from being read whilst the message box is active.

Lastly, none of this will work if someone disables their macros!

Questions & Answers


      0 of 8192 characters used
      Post Comment
      • LiamBee profile imageAUTHOR


        2 months ago from UK


        In step 3, user will contain the username. You can then use "user" later and it's value will have the username in it. As for reversing the list. In step 5, swap the true and false on the access variables. So outside of the loop declare "access" as true first, then inside the loop make it false

      • profile image


        2 months ago

        I am having troubles with this. I do not know where my user name will be displayed in step 3. Also I would like to do the opposite if this VBA. I would like whoever is on the list to not have access. Can you help?

      • profile image


        11 months ago

        Hi There,

        I am new on VBA so I am not getting it that way.

        Can i have a .xlsx file of this article at


        Bilal Yousaf


      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

      Show Details
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
      ClickscoThis is a data management platform studying reader behavior (Privacy Policy)