I have an excel workbook with multiple sheets. Is there any way to password protect users from even opening a sheet within the workbook? The sheet has a large graph on it that I don't want everyone to be able to see, let alone edit.
Thanks in advance for your help
EDIT
I used the following code to allow users to click a formcontrol button to access the sheet in question.
Sub ShowHeatMap()
Dim S As String
S = InputBox("Enter Password")
If S = vbNullString Then
Exit Sub
ElseIf S <> "wiretransfer" Then
Exit Sub
Else
Worksheets("Training Heat Map").Visible = xlSheetVisible
End If
End Sub
This is associated with my button on a kind of "homepage" sheet that I added to the workbook.
But I can't get the sheet to remain hidden when you open the workbook again. I tried this code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Worksheets("Training Heat Map").Visible = xlSheetVeryHidden
End Sub
Any ideas? This code is inputted on the module for the sheet under general declarations
Via this answer, I think this might do the trick for you. Within VBA, put this within ThisWorkbook:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheets As String, Response As String
MySheet = "Sheet1"
If ActiveSheet.Name = MySheet Then
ActiveSheet.Visible = False
Response = InputBox("Enter password to view sheet")
If Response = "MyPass" Then
Sheets(MySheet).Visible = True
Application.EnableEvents = False
Sheets(MySheet).Select
Application.EnableEvents = True
End If
End If
Sheets(MySheet).Visible = True
End Sub
Obviously will require a bit of tailoring to your needs. Remember that you will also need to password protect your VBA code, otherwise anyone will be able to view it and find out the password.
Related
Hope someone can help - I have a Userform that opens on launch of the excel file (Test.xlsm) and hides the workbook from prying eyes. The workbook can become visible for editing by a button click and password entry from the userform. Everything is working fine - UNTIL - you open another instance of excel. Once you finish with it and close any secondary instance of excel, it also either
1. closes the userform, or
2. shows the excel workbook behind the userform. Neither of these is what I want. I need the userform to remain open and I need the workbook associated with it to remain hidden until called.
Question - is there some code that will prevent other instances of excel from doing what it is doing, or am I dreaming.
I found some code (below) that the writer said done exactly what i am after, but all I got was global errors.
Private Sub WorkBook_Open()
If Workbooks.Count = 1 Then Application.Visible = False
Workbooks("test.xlsm").Windows(1).Visible = False
UserForm1.Show vbModeless
End Sub
Any help greatly appreciated.
BTW - the code for the workbook open is
Private Sub Workbook_Open()
Set Thiswb = Me.Application
Application.Visible = False
Staff_Contacts.Show vbModeless
End Sub
For usecase you described, I would propose you something similar to this solution:
Sub Workbook_open()
Dim wrong_attempts As Integer
wrong_attempts = 0
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
ActiveWorkbook.Sheets("Sheet2").Visible = xlSheetVeryHidden
Start1:
If wrong_attempts > 4 Then
MsgBox "You've entered wrong password too many times. File will now be closed"
Application.DisplayAlerts = False
sheet.Delete
ActiveWorkbook.Close
Application.DisplayAlerts = True
End If
InputBoxVariable = InputBox(Prompt:="Please enter password to access this document", Title:="Authorization required", Default:="")
If InputBoxVariable = "12345" Then
ActiveWorkbook.Sheets("Sheet2").Visible = xlSheetVisible
Application.DisplayAlerts = False
sheet.Delete
Application.DisplayAlerts = True
Else
wrong_attempts = wrong_attempts + 1
GoTo Start1
End If
End Sub
In this example it is assumed that sheet2 should be protected. On the very load of the document, phantom sheet will be created, and after successful login, it will be deleted and sheet2 should be visible again. In addition, if someone enters wrong password 5 times, file closes automatically.
Fair notice, I've used InputBox out here, so password is not masked, if you want to mask password as well, you will have to make brand new form with button and textbox.
I thought this would be a readily used function in Excel but it's surprisingly difficult to implement a simple process of restricting access to specific worksheets within a larger workbook.
There's a few methods that prompt an initial password to open various versions of the same workbook. But I want to keep the workbook identical for all users but restrict access to certain sheets. Surely there's a password protect function that requires the user to enter a password to view a sheet. Rather than create multiple versions of the same workbook based on different users.
I have tried the following but it doesnt prompt a password to access the sheet
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheets As String, Response As String
Dim MySheet As Worksheet
MySheet = "COMMUNICATION"
If ActiveSheet.Name = MySheet Then
ActiveSheet.Visible = False
Response = InputBox("Enter password to view sheet")
If Response = "MyPass" Then
Sheets(MySheet).Visible = True
Application.EnableEvents = False
Sheets(MySheet).Select
Application.EnableEvents = True
End If
End If
Sheets(MySheet).Visible = True
End Sub
Am I doing this right?
It sounds like according to the comments that this isn't as much as a security issue as it is a convenience issue. So please bear in mind when considering implementing this into your project that this is easily breakable if there is any malicious intent to gain unauthorized access.
First, I would recommend a common landing zone. A main worksheet that is displayed immediately after opening a workbook. To do this, we would use the Workbook_Open() event and activate a sheet from there.
This can be a hidden sheet if desired, that will be up to you.
Option Explicit
Private lastUsedSheet As Worksheet
Private Sub Workbook_Open()
Set lastUsedSheet = Me.Worksheets("MainSheet")
Application.EnableEvents = False
lastUsedSheet.Activate
Application.EnableEvents = True
End Sub
Next, we should decide on what should occur when there's an attempt to access a new sheet. In the below method, once a sheet is activated it will automatically redirect the user back to the last used sheet until a successful password attempt has been made.
We can track the last used sheet in a module-scoped variable, which in this example will be named lastUsedSheet. Any time a worksheet is successfully changed, this variable will be set to that worksheet automatically - this way when when someone attempts to access another sheet, it will redirect them back to the prior sheet until the password is successfully entered.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
On Error GoTo SafeExit
Application.EnableEvents = False
' Error protection in case lastUsedSheet is nothing
If lastUsedSheet Is Nothing Then
Set lastUsedSheet = Me.Worksheets("MainSheet")
End If
' Allow common sheets to be activated without PW
If Sh.Name = "MainSheet" Then
Set lastUsedSheet = Sh
Sh.Activate
GoTo SafeExit
Else
' Temporarily send the user back to last sheet until
' Password has been successfully entered
lastUsedSheet.Activate
End If
' Set each sheet's password
Dim sInputPW As String, sSheetPW As String
Select Case Sh.Name
Case "Sheet1"
sSheetPW = "123456"
Case "Sheet2"
sSheetPW = "987654"
End Select
' Create a loop that will keep prompting password
' until successful pw or empty string entered
Do
sInputPW = InputBox("Please enter password for the " & _
"worksheet: " & Sh.Name & ".")
If sInputPW = "" Then GoTo SafeExit
Loop While sInputPW <> sSheetPW
Set lastUsedSheet = Sh
Sh.Activate
SafeExit:
Application.EnableEvents = True
If Err.Number <> 0 Then
Debug.Print Time; Err.Description
MsgBox Err.Description, Title:="Error # " & Err.Number
End If
End Sub
Side note, disabling events is necessary due to the fact that your Workbook_SheetActivate event will continue to fire after a successful sheet change.
Preventing file type changes during SaveAs1
You can further protect the accidental removal of VBA code by restricting the file save type. This can be accomplished using the Workbook_BeforeSave() event. The reason this is a potential problem is that saving as a non-macro enabled workbook will erase the code, which will prevent the password protection features you just implemented above.
First, we need to check if this is a Save or SaveAs. You can accomplish this using the Boolean property SaveAsUI that is included with the event itself. If this value is True, then it's a SaveAs event - which means we need to perform additional checks to ensure that the file type isn't accidentally changed from the save dialog box. If the value is False, then this is a normal save, and we can bypass these checks because we know the workbook will be saved as type .xlsm.
After this initial check, we will display the dialog box using Application.FileDialog().Show.
Afterwards, we will check if the user canceled the operation .SelectedItems.Count = 0 or clicked Save. IF user clicked cancel, then we simply set Cancel = True and the workbook will not save.
We proceed to check the type of extension selected by the user using this line:
If Split(fileName, ".")(UBound(Split(fileName, "."))) <> "xlsm" Then
This will split the file path by a period ., and will grab the last instance of the period (UBound(Split(fileName, "."))) in the event a file name may contain additional periods. If the extension does not match xlsm, then we abort the save operation.
Finally, after all checks passed, you can save the document:
Me.SaveAs .SelectedItems(1), 52
Since we already saved it with the above line, we can go ahead and set Cancel = True and exit the routine.
The full code (to be placed in the Worksheet obj module):
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
On Error GoTo SafeExit
If SaveAsUI Then
With Application.FileDialog(msoFileDialogSaveAs)
.Show
If .SelectedItems.Count = 0 Then
Cancel = True
Else
Dim fileName$
fileName = .SelectedItems(1)
If Split(fileName, ".")(UBound(Split(fileName, "."))) <> "xlsm" Then
MsgBox "You must save this as an .xlsm document. Document has " & _
"NOT been saved", vbCritical
Cancel = True
Else
Application.EnableEvents = False
Application.DisplayAlerts = False
Me.SaveAs .SelectedItems(1), 52
Cancel = True
End If
End If
End With
Else
Exit Sub
End If
SafeExit:
Application.EnableEvents = True
Application.DisplayAlerts = True
If Err.Number <> 0 Then
Debug.Print Time; Err.Description
MsgBox Err.Description, Title:="Error # " & Err.Number
End If
End Sub
1 Shoutout to PatricK for the suggestion
If you want to restrict access to a worksheet, you can just hide it:
ActiveWorkbook.Sheets("YourWorkSheet").Visible = xlSheetVeryHidden
I concur with Mathieu Guindon that any VBA attempt to "Restrict viewing access to an Excel worksheet" will be flimsy as explained by Mathieu Guindon. Moreover, If the file is opened with Excel option Macro security level other than the lowest, any VBA code including this is bound to fail.
However just for shake of simplicity I prefer to use workbook open event and Sheet Activate of the restricted sheet. Using Workbook Sheet Activate event will trigger password prompt even during switching between sheets by user with viewing access.
Private Sub Workbook_Open()
Sheets("COMMUNICATION").Visible = xlSheetHidden
End Sub
Public ViewAccess As Boolean 'In restricted sheet's activate event
Private Sub Worksheet_Activate()
If ViewAccess = False Then
Me.Visible = xlSheetHidden
response = Application.InputBox("Password", xTitleId, "", Type:=2)
If response = "123" Then
Me.Visible = xlSheetVisible
ViewAccess = True
End If
End If
End Sub
I have an excel workbook containing several worksheets.
What I want to do is have a mechanism like a user form or something where the user would authenticate to one of several possible users.
Based on the username supplied I want to display certain worksheets and hide other sheets, and block the user from accessing worksheets they should not be able to view.
Has anyone done something like this in Excel?
Any thoughts are appreciated
Sean
I actually enjoyed the task of typing this one up. Keep in mind, VBE is not protected in this code so you may want to add some protection, but this should do what you need.
You should also create a generic Login worksheet. This would be the only sheet open before a password is entered. This is essential as you are unable to hide every sheet without throwing an error. (You need to have 1 visible sheet).
WARNING: This code is mildly tested. You are responsible for any loss of data for using the below code, such as (but not limited to) forgetting a password. You have been warned!!!!
1. Open the Workbook, then make a Call to GetLogin
Option Explicit
Private Sub Workbook_Open()
GetLogin 1
End Sub
2. The Login Code
Private Sub GetLogin(ByVal AttemptNumber As Integer)
Dim Sheet As Worksheet
With ThisWorkbook.Worksheets("Login")
.Visible = xlSheetVisible
.Activate
End With
For Each Sheet In ThisWorkbook.Sheets
If Not Sheet.Name = "Login" Then
Sheet.Visible = xlSheetVeryHidden
End If
Next Sheet
Dim Password As String
Password = Application.InputBox("Please enter your password")
Select Case Password
Case "Ma$terPas$"
For Each Sheet In ThisWorkbook.Sheets
Sheet.Visible = xlSheetVisible
Next Sheet
ThisWorkbook.Worksheets(1).Activate 'For when you hide login sheet
Case "Oth3Rpa$$"
With ThisWorkbook
.Worksheets(1).Visible = xlSheetVisible
End With
ThisWorkbook.Worksheets(1).Activate 'For when you hide login sheet
Case Else
If AttemptNumber <= 3 Then
If MsgBox("You entered an incorrect password", vbRetryCancel, "Attempt # " & AttemptNumber) = vbRetry Then
AttemptNumber = AttemptNumber + 1
GetLogin AttemptNumber
Else
ThisWorkbook.Saved = True
ThisWorkbook.Close
End If
Else
ThisWorkbook.Saved = True
ThisWorkbook.Close
End If
End Select
ThisWorkbook.Worksheets("Login").Visible = xlSheetHidden
End Sub
3. Close the Workbook
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If ThisWorkbook.Saved = False Then
If MsgBox("Would you like to save?", vbYesNo) = vbYes Then
ThisWorkbook.Save
End If
End If
Dim Sheet As Worksheet
With ThisWorkbook.Worksheets("Login")
.Visible = xlSheetVisible
.Activate
End With
For Each Sheet In ThisWorkbook.Sheets
If Not Sheet.Name = "Login" Then
Sheet.Visible = xlSheetVeryHidden
End If
Next Sheet
'Prevent from being asked to save the fact you just hid the sheets
ThisWorkbook.Saved = True
End Sub
Ensure that the Workbook_Open and Workbook_Close are in your Workbook's Module.
You could probably achieve this by using the Auto_Open event
Function Auto_Open()
Select Case True
Case InStr(Application.UserName, "Dan Smith") > 0
ActiveWorkbook.Sheets(1).Visible = xlSheetVeryHidden
Case InStr(Application.UserName, "Jon Doe") > 0
ActiveWorkbook.Sheets(1).Visible = True
End Select
End Function
Of course this would take a lot of work considering you'd have to find out everyone's usernames and then the sheets that you want to hide from them, but that's what I thought of
Trying to work out how only I can see the work book and everyone else can see the userform, based on network username.
Here's what I've got so far:
Private Sub Workbook_Open()
Application.Visible = False
UtilitiesReportingTool.Show
End Sub
You'll need a couple of things to stop your users looking at your worksheets - and these can easily be broken with a little knowledge.
Create a sheet with big text saying "Please enable macros"
Very hide all sheets except the macro enable sheet.
Create these two procedures in a normal module
Sub StartUp()
Dim wrkSht As Worksheet
If Environ("username") <> "CAES_MATT" Then
Application.Visible = False
UtitlitiesReportingTool.Show
Else
For Each wrkSht In ThisWorkbook.Worksheets
wrkSht.Visible = xlSheetVisible
Next wrkSht
End If
End Sub
Sub ShutDown()
Dim wrkSht As Worksheet
For Each wrkSht In ThisWorkbook.Worksheets
Select Case wrkSht.CodeName
Case "Sheet1" 'This should really be shtMacroEnable or something.
wrkSht.Visible = xlSheetVisible
Case Else
wrkSht.Visible = xlSheetVeryHidden
End Select
Next wrkSht
End Sub
In your Workbook_Open event add this code:
Private Sub Workbook_Open()
StartUp
End Sub
In your UserForm_Terminate event add this:
Private Sub UserForm_Terminate()
Application.Visible = True
ShutDown
End Sub
When you open the workbook only the 'Enable Macros' sheet will be visible if macros aren't enabled.
When macros are enabled the form is displayed, unless it's you in which case all the sheets are unhidden.
When the form is closed everything except the sheet with codename Sheet1 is hidden.
I may have missed something ... heading home.
New here and I just started to teach myself coding. I have a workbook that has roughly 14 tabs/worksheets for employees to enter their hours worked per day. On a "Summary" tab and want to create a macro button for each employee to click on to view his/her tab. These employee tabs are hidden and all I want the action to do is unhide and then hide when the employee clicks their button.
Unfortunately, I receive an Ambiguous Error message and I created a module per employee. I assume I need to somehow "stack" code, but again am totally new to coding. Below is a sample of my code
Private Sub ShowHideWorksheets()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
you need to correctly put it behind a button. When you insert the button into the page, right click it and assign macro. The code would look like
Sub Button1_Click()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
Basically you wish to toggle visibility for a worksheet.
Assuming that you know which Sheet is going to be triggered, it is something like this:
Public Sub TriggerSheetVisibility(worksheetname as string)
Dim ws as WorkSheet
On Error Resume Next 'To avoid subscript out of range error if a worksheetname is passed that doesn't exit
Set ws = Worksheets(worksheetname)
On Error Goto 0
If Not ws Is Nothing Then 'Only when the worksheet exists, we can execute the rest of this sub:
If ws.Visible = True then
ws.Visible = False
Else
ws.Visible = True
End If
End If
End Sub
Also see https://msdn.microsoft.com/en-us/library/office/ff197786.aspx
This is also an acceptable approach? Prolly long winded though
Private Sub CommandButton1_Click()
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Sheets
If sheet.Name <> CommandButton1.Caption Then
sheet.Visible = False
End If
If sheet.Name = CommandButton1.Caption Then
sheet.Visible = True
End If
Next sheet
End Sub
However I like this better due to the fact you only need one button
Private Sub CommandButton1_Click()
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Sheets
If sheet.Name <> Environ("USERNAME") Then
sheet.Visible = False
End If
If sheet.Name = Environ("USERNAME") Then
sheet.Visible = True
End If
Next sheet
End Sub
If you change Private to Public it should work. I'm presuming you're just creating macros at this point to get base functionality to work. You can hide (as the code you've posted) and unhide like this:
' This first macro actually just makes the worksheet visible and then
' invisible each time you execute it - so I'm not sure if
' that's what you're after
Public Sub ShowHideWorksheets()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
' If it's invisible you can do this.
Public Sub ShowWorksheets()
Sheets("EMPLOYEE 1").Visible = True
End Sub
' Basically that should give you an idea of how to proceed.