Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA hide sheets from specific users

Tags:

excel

vba

Looking for some help on VBA User restrictions. So far I have the code pasted below. It is working perfectly, but I want to build on it.

I have it so the specific users listed have access to the file, and anyone else who tries to access the file gets a msgbox saying they aren't authorized and then the book closes.

I am however hoping that some of the users can see some sheets (the sheets they shouldn't see will be xlveryhidden) And then the other users can see the other sheets listed...

ie: Name 1 can see sheet 13, Name2 can see sheet14 and sheet3 Name 3 can see sheet22 sheet23 and sheet4 In terms of security it isn't hugely important, they are all from the same team, but just for user friendly and tidy document.

Private Sub Workbook_Open()
 Dim Users As Variant
 Dim UName As String
 Dim UFind As Variant
 Users = Array("Name1", "Name2", "Name3", "Name4", "Name5")

 UName = Environ("UserName")
 On Error Resume Next
 UFind = WorksheetFunction.Match(UName, Users, 0)
 If Err <> 0 Then
     MsgBox "You are not authorised to use this Workbook"
     ThisWorkbook.Close SaveChanges:=False
 End If
End Sub
like image 257
user5836742 Avatar asked Mar 07 '26 02:03

user5836742


1 Answers

Came up with an answer, it is pretty simple, and wont withstand new users being added, but for the mean time it is ok...

Private Sub Workbook_Open()
 Dim Users As Variant
 Dim UName As String
 Dim UFind As Variant
 Users = Array("Name1", "Name2", "Name3")

 UName = Environ("UserName")
 On Error Resume Next
 UFind = WorksheetFunction.Match(UName, Users, 0)
 If UName = "Name2" Then
 Worksheets("Sheet23").Visible = True
 Worksheets("SHEET17").Visible = True

 ElseIf UName = "Name1" Then
 Worksheets("Sheet23").Visible = True
 Worksheets("SHEET17").Visible = True
 Worksheets("Sheet4").Visible = True


 ElseIf UName = "Name3" Then
 Worksheets("Sheet23").Visible = True
 Worksheets("SHEET17").Visible = True

 ElseIf Err <> 0 Then
     MsgBox "You are not authorised to use this Workbook"
     ThisWorkbook.Close SaveChanges:=False
 End If
 End Sub

And in order to re-hide them all again when closing the file:

SubPrivate Sub Workbook_BeforeClose(Cancel As Boolean)

Worksheets("Sheet23").Visible = False
Worksheets("SHEET17").Visible = False
Worksheets("Sheet4").Visible = False
Worksheets("Sheet1").Visible = False

‘If you don’t save it’s not effective
Me.Save End Sub
like image 194
user5836742 Avatar answered Mar 08 '26 20:03

user5836742



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!