Home » excel » vba – Row level security in Excel – what approach should I use:

vba – Row level security in Excel – what approach should I use:

Posted by: admin April 23, 2020 Leave a comment

Questions:

Morning folks,

Over the last couple of days I have been trying to find a way of implementing “pseudo” row level security in Excel using VBA macros.
What I require is to filter all of my Excel table based on the Windows user credentials. The problem is that I am not sure how to tackle this issue and this is the only idea I have so far:

 1.Derive the NT account and store it in namedrange
 2. Use autofilter based on NamedRange for each table in my spreadsheet
 3. Delete / Hide the unnecessary rows ?

Example:

enter image description here

Perhaps, there are other ways which are more suitable for my scenario, however I havent been able to find them.
If you could point me into the right direction, I would appreciate it.

Thanks

How to&Answers:

This can be achieved by pasting the following into the ThisWorkBook Module in your specific WorkBook VBA project. Just remember to save the WorkBook as a .dotm

As mentioned by J.Chomel bypassing WorkBook passwords is not the hardest thing to do and you could find a macro to do that on the net.

Obviously you will need to password protect your VBA project as well to prevent users from accessing the WorkBook password from there.

 Private Sub Workbook_Open()

      Dim CurrentUserName As String
      CurrentUserName = Environ("Username")

      Dim WorkBookPassword As String
      'Replace password with your desired password
      WorkBookPassword = "password"

      Dim DataWS1 As Worksheet
      'Replace Sheet1 with your specific sheet name
      Set DataWS1 = ThisWorkbook.Sheets("Sheet1")

      With DataWS1

           .Unprotect WorkBookPassword

           If .AutoFilterMode Then .AutoFilterMode = False

           .UsedRange.AutoFilter Field:=3, Criteria1:=CurrentUserName

           .Protect Contents:=True, _
                    AllowFiltering:=False, _
                    UserInterfaceOnly:=True, _
                    Password:=WorkBookPassword
      End With

 End Sub

Answer:

To implement row level security in Excel, you should avoid retrieving the data in Excel in the first place. Because if you use vba to filter, it will easily be bypassed by some users. So it could not be called security.