My goal is to protect sheets with password.
So when user open the workbook I want that all sheets except one will be hidden( Very hidden). When user enter the password all sheets will be visible. How can I hide and show lot of sheets using vba code, is there any simple techniques? I mean is it possible to hide "Tab selection facility"?
Before, let me point out how Excel files are not secure:
Your code will be part of the file's XML, so inspecting the underlying data, anyone who wants to can find out how to get your password.
Now that you've been warned, here the code that you must include at the workbook open event. It will hide everything (to prevent scenarios where the sheets would have been left visible upon closing the book), then ask a password.
Public Sub UnlockSheets()
' 1 - hide every sheet, except the desired one
Dim aWorksheet As Worksheet
For Each aWorksheet In ActiveWorkbook.Worksheets
If aWorksheet.Name <> "desired sheet name" Then
aWorksheet.Visible = xlVeryHidden
Next
' 2 - ask for the password
Dim userPassword As String
userPassword = InputBox("Please enter your password")
If userPassword = "my_password" Then
RevealSheets
Else
MsgBox "Wrong password!", vbCritical
Application.DisplayAlerts = False
ActiveWorkbook.Close False
End If
End Sub
Public Sub RevealSheets()
'3 - Hide all the sheets
Dim aWorksheet As Worksheet
For Each aWorksheet In ActiveWorkbook.Worksheets
aWorksheet.Visible = xlSheetVisible
Next
End Sub
Another problem here is that the user can stop all macros by holding the SHIFT key (if I recall right). Needless to say... it's not too secure. Then again, Excel files aren't known for incredible safety.
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'm trying to use the following code to open a password protected file if the Windows user is "bhope" or "jdean" and display a message box if the user is anyone else. It opens the file as needed when the user is "bhope" or "jdean" but if another user clicks the button, nothing happens/no error. What am I missing?
Sub Button1_Click()
Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")
Application.ScreenUpdating = False
Select Case strUser
' Full Workbook Access
Case Is = "bhope", "jdean"
If ActiveWorkbook.ReadOnly Then _
Set wb = Workbooks.Open(Filename:="M:\...", Password:="TEST")
' Limit Access
Case Is = "mjackson" 'also tried "Case Is <> "bhope", "jdean"
If Not ActiveWorkbook.ReadOnly Then _
MsgBox ("This button is reserved for SAMs")
End Select
Application.ScreenUpdating = True
End Sub
If it helps, I used this link to start the base of the code and tried to modify it from there. Thanks and cheers!
Your use of IS here may be the culprit. At best it's superfluous, at worse it's masking this issue. Instead try:
Sub Button1_Click()
Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")
Application.ScreenUpdating = False
Select Case strUser
' Full Workbook Access
Case "bhope", "jdean"
If ActiveWorkbook.ReadOnly Then _
Set wb = Workbooks.Open(Filename:="M:\...", Password:="TEST")
' Limit Access
Case "mjackson"
If Not ActiveWorkbook.ReadOnly Then _
MsgBox ("This button is reserved for SAMs")
End Select
Application.ScreenUpdating = True
End Sub
Also consider changing that second CASE to CASE ELSE.
The other thing is that your msgbox is inside of your IF condition. strUser must be uqual to mjackson AND the ActiveWorkbook (whatever that might be at the time this code executes) must NOT be ReadOnly for that msgbox to fire.
Consider changing "ActiveWorkbook" to be more specific. Perhaps ThisWorkbook.ReadOnly?
Consider an Else for your if statement to see if the mjackson is hitting but the readonly is not:
Case "mjackson"
If Not ActiveWorkbook.ReadOnly Then
MsgBox ("This button is reserved for SAMs")
Else
MsgBox ("ActiveWorkbook is not Read Only so yo get this message")
End If
Lastly, put a breakpoint (F9) on SELECT and see what your value of strUser as while the code is running (hover over strUSer on that line or check your Locals pane). You may also want to see what ActiveWorkbook is at this point of time too, just in case. The answer will, again, be in your Locals pane, so make sure that is turned on in the view drop down of VBE.
I figured out the solution. Apparently the "case else" I said I tried earlier was actually done to another test file with similar code as I usually have several open when I'm testing to compare behaviors. I also had to delete the line below "case else" so that only the msg box line would run after that. Below is the code I used should anyone need it in the future:
Sub Button1_Click()
Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")
Application.ScreenUpdating = False
Select Case LCase(strUser)
' Full Workbook Access
Case Is = "bhope", "jdean"
If ThisWorkbook.ReadOnly Then _
Set wb = Workbooks.Open(Filename:="M:...", Password:="TEST")
' Limit Access
Case Else
MsgBox ("This button is reserved for SAMs")
End Select
Application.ScreenUpdating = True
End Sub
To answer earlier questions: my understanding of screen update is that if it's turned off, the application will run non-visually so as not to cause concern for the users who will be using this file. Also, this code makes it run faster, does it not?
As far as the purpose of the workbook and security concerns... the button will be used on a read only workbook that houses many portions of our company's metrics. The file is made read only so that users cannot save over it. Since the file is kind of big and a lot of data is expected to go into it, my thought process was to load the "Shell" of the main file then have buttons that determine who should be allowed to add info to certain sheets. By having both files read only and password-protected, I'm able to open the 2nd sheet when the appropriate user clicks the button, then have data transfer back and forth between the workbooks. I still intend on password protecting the VBA code so I don't see how their could be a security concern. Also, #ashleedog, I meant that everyone in our company has lower case user names.
What I would like to do is create a user login and password to get into an excel file. Meaning, when they click the file to open they immediately get taken to the login sheet I have and if the password is wrong the get denied access and the book closes. This is the code that I have so far which works while you are in excel.
Private Sub Workbook_Open()
Dim Sh As Worksheet
Dim UserName As String
Dim Password As String
Dim ThisCell As Range
Dim c As Long
For Each Sh In ThisWorkbook.Worksheets
If Sh.Name <> "WELCOME SCREEN" Then
Sh.Visible = Sheet4
End If
Next Sh
UserName = InputBox("Please enter your user name.")
Password = InputBox("Please enter password.")
For Each ThisCell In Sheets("Sheet4").Range("A2:A" & Sheets("Sheet4").Range("A65536").End(xlUp).Row)
If UCase(ThisCell.Value) = UCase(UserName) And UCase(ThisCell.Offset(, 1).Value) = UCase(Password) Then
MsgBox "Access Granted"
For c = 2 To 4
'This is the number of sheets from C1 to E1
If ThisCell.Offset(, c).Value <> "" Then
Sheets(Sheets("Sheet4").Cells(1, c + 1).Value).Visible = xlSheetVisible
End If
Next c
Exit Sub
End If
Next ThisCell
MsgBox "Access Denied"
ThisWorkbook.Close
End Sub
Where Sheet4 is a hidden sheet that contains all of the usernames and passwords. Any help would be greatly appreciated!
Instead of rolling your own security in a macro which is easily defeated (as documented the the comments on your OP), why don't you just take advantage of the built in Excel password protection that is available from the Save dialogue box? (Click the Tools drop down, just in case it wasn't explicitly clear)
You can then distribute the password to those who need to know. If there is a high likelihood of people passing the password to those who shouldn't have it, change it regularly...
There may well be fragility in the Microsoft password facility (I'm not aware of any, some Googling aught to tell you), but I'm pretty certain it's more secure than your proposal.
I have been trying to fix a login problem but I cannot find a solution. When both login and pass fail, an error message starts a countdown without letting the user manifest another opinion.
QUESTION 1: Can anyone please make the necessary corrections without altering too much the given code structure and explain?
QUESTION 2: What code would turn the "User1" text into bold at the moment the access is granted?
QUESTION 3: What command would disable the "X" on the top right-hand corner of the msg form?
Thank you in advance
Here it is what I could do
¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
Private Sub BtOK_Click()
Dim User1 As String
Dim count As Integer
count = 3
MM:
If EDBoxlogin.Value = "admin" And EDBoxpass.Value = "1234" Then
User1 = Application.UserName
MsgBox "welcome" & User1 & " !", vbExclamation, "Access Granted"
Sheets("Plan1").Visible = xlSheetVisible
Unload Me
Else
If EDBoxlogin.Value = "" Or EDBoxpass.Value = "" Then
MsgBox "Please, fill in the fiels 'login' and 'pass'", vbExclamation + vbOKOnly, "Access denied : incomplete information"
Else
If count >= 0 Then
MsgBox "Login and pass are incorrect! You have " & count & " more trial(s)", vbExclamation + vbOKOnly, "Access denied"
EDBoxlogin.Value = "" And EDBoxpass.Value = ""
' I want to delete previous text in the editbox fields
count = count - 1
GoTo MM
Else
ThisWorkbook.Close
End If
End If
End If
End Sub
If you don't really need to know which user is opening the workbook, consider using Excel's built-in password security function. Also, you should encrypt the contents of the file also using Excel's built-in functions, or anyone can open the file with a text editor and find the userID and password listed in your code.
If you must use a login form, and I've also had to do so in the past, the following code builds on what you did by adding a user list to a hidden worksheet Users. Column A in that sheet needs to be the user names, B contains the passwords. This worksheet also uses cell D1 to track failed login attempts. Using variables in code for this sort of thing is tough ... you have to make them Public and if there are any errors when running code, it will lose its value, then bad things can happen.
The code also references another sheet, SplashPage. This allows you to hide Project1 when the user exits the workbook. The code I wrote handles the hide/unhide process when the file is opened or closed.
I don't know a way to turn off the close box in a user form. I've added code to reject the login if a user does that.
Happy coding.
'Module: frmLogin
Private Sub BtOK_Click()
Dim User1 As String
Dim Passwd As Variant
Sheets("Users").Range("D2").Value = False
User1 = EDBoxlogin.Value
Passwd = getPassword(User1)
If User1 <> "" And Passwd <> "" And EDBoxpass.Value = Passwd Then
Sheets("Users").Range("D2").Value = True
MsgBox "Welcome " & User1 & "!", vbExclamation, "Access Granted"
With Sheets("Plan1")
.Visible = xlSheetVisible
.Activate
End With
Sheets("SplashPage").Visible = xlSheetVeryHidden
Unload Me
Exit Sub
Else
Sheets("Users").Range("D1").Value = Sheets("Users").Range("D1").Value - 1
If Sheets("Users").Range("D1").Value > 0 Then
MsgBox "Login and pass are incorrect! You have " & Sheets("Users").Range("D1").Value & _
" more trial(s)", vbExclamation + vbOKOnly, "Access denied"
EDBoxpass.Value = ""
With EDBoxlogin
.Value = ""
.SetFocus
End With
' I want to delete previous text in the editbox fields
Exit Sub
End If
End If
UserForm_Terminate
End Sub
Private Sub UserForm_Terminate()
If Sheets("Users").Range("D2").Value <> True Then
MsgBox "Login cancelled, goodbye!"
doWorkbookClose
End If
End Sub
'Module: ThisWorkbook
Private Sub Workbook_BeforeClose(Cancel As Boolean)
doWorkbookClose
End Sub
Private Sub Workbook_Open()
On Error Resume Next
Sheets("Users").Range("D1").Value = 3
With Sheets("SplashPage")
.Visible = xlSheetVisible
.Activate
End With
Sheets("Plan1").Visible = xlSheetVeryHidden
Sheets("Users").Visible = xlSheetVeryHidden
ThisWorkbook.Save
frmLogin.Show
End Sub
'Module: Module1
Function getPassword(strVarib As String) As Variant
Dim r As Long
Dim sht As Worksheet
Dim rng As Range
On Error GoTo ErrorHandler
Set sht = Sheets("Users")
Set rng = sht.Range("A:A")
r = WorksheetFunction.Match(strVarib, rng, 0)
getPassword = sht.Cells(r, 2).Value
Exit Function
ErrorHandler:
getPassword = Empty
End Function
Sub doWorkbookClose()
On Error Resume Next
With Sheets("SplashPage")
.Visible = xlSheetVisible
.Activate
End With
Sheets("Plan1").Visible = xlSheetVeryHidden
Sheets("Users").Visible = xlSheetVeryHidden
ThisWorkbook.Save
End Sub
[begin Q&A]
Luiz, I've answered your edits below.
'Q: What Passwd does?
'Module: frmLogin
....
Passwd = getPassword(User1)
A: It gets the password value matching the value of User1. Here's the whole function for context:
Function getPassword(strVarib As String) As Variant
Dim r As Long
Dim sht As Worksheet
Dim rng As Range
On Error GoTo ErrorHandler
Set sht = Sheets("Users")
Set rng = sht.Range("A:A")
r = WorksheetFunction.Match(strVarib, rng, 0)
getPassword = sht.Cells(r, 2).Value
Exit Function
ErrorHandler:
getPassword = Empty
If User1 does not exist then WorksheetFunction.Match throws an error and code execution will jump to ErrorHandler:.
'Q: Does Empty mean that the cell is not with zeros or spaces, but completely blank instead?
A: Empty refers to a Variant variable type that is set to its default value. getPassword could just as easily return the boolean False or integer 0 because those are the default values for those types. It's actually not strictly necessary to set getPassword to anything here ... it's just my personal practice to be explicit.
Since IsEmpty(celFoo) is a valid test for whether a cell is empty or not, you might want to return False instead of Empty to avoid ambiguity.
'Q: Can you explain these two lines below in detail?
Set sht = Sheets("Users")
Set rng = sht.Range("A:A")
A: It's just habit. The alternative would be to elminate those variable assignments and rewrite this line:
r = WorksheetFunction.Match(strVarib, rng, 0)
as:
r = WorksheetFunction.Match(strVarib, Sheets("Users").Range("A:A"), 0)
which is messier to type. Especially if we're going to be doing other things on that sheet with that range in the same routine. Which we are in the next block of code ...
'Q: Important to explain these three lines below in detail too [why 0?, To where (r,2) points to?]
r = WorksheetFunction.Match(strVarib, rng, 0)
getPassword = sht.Cells(r, 2).Value
Exit Function
A: To review, worksheet Users contains user IDs in column A, and their passwords in column B. There can be as many users as there are rows in a worksheet.
- rng is column A as set above.
- 0 means find an exact match for strVarib and throw an error if not match is found.
- If we find a match, r will be set to the row number where the value in column A is equal to our input parameter, strVarib.
- So, sht.Cells(r, 2).Value is the password value in column B (column 2) for the UserID.
'Q: Why the need to call a splashpage? What it contains?
A: You don't necessarily need one, but if you really want to secure your workbook it's good practice. Let's say that it contains sensitive information that you don't want unauthorized user to see. At the very least you would:
Encrypt the worbook using native Excel functionality.
Password protect your VBA project using native functionality. This keeps savvier users from reading your code and making the xlSheetVeryHidden sheets Users and Plan1 visible to their prying eyes.
Now, you can't hide all sheets in a workbook at the same time, at least one needs to be visible at any given time ...
... so I've created a third sheet called SplashPage that doesn't contain any sensitive information. And that means I can hide all of the other worksheets until the user enters a valid UserID and password in frmLogin.
SplashPage can contain whatever you want. You can call it whatever you want. Typically, mine says something like:
Welcome to the Enemies List Application!
Only authorized users may access this workbook.
If you're seeing this page and no login form is visible
it means you've disabled the macros in this workbook.
Please make sure macro security is set to "Medium"
then close Excel entirely, reopen this file
and select "Enable Macros" when prompted.
If you attempt to view or modify this file without proper
authorization you will be added to the list herein.
-[Signed] Richard M. Nixon
A really really secure workbook would not contain the users and passwords in a hidden sheet. In fact, I never do this. Most of my apps are database driven, and I authenticate users against both the domain and a custom table in the application database. This effectively keeps anyone from using it unless they're onsite and connected to the network. I also usually flush all the data from the relevant worksheets when the user closes the workbook to a) keep the file size smaller and b) keep sensitive data from being stored in it and taken offsite. But that's beyond the original scope of your question.
'Why is [the following] necessary? What is being saved? Purpose?
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Save
A: There are two scenarios for closing the application: 1) a failed login attempt and 2) a successful login by a user who has finished making changes.
Take case (2) first. We want to hide all the sensitive information before closing so that the next person who opens the file only sees SplashPage and the login form. We know the user is closing the workbook because we have this code in the ThisWorkbook module BeforeClose event script:
'Module: ThisWorkbook
Private Sub Workbook_BeforeClose(Cancel As Boolean)
doWorkbookClose
End Sub
All it does is call this subroutine in Module1:
Sub doWorkbookClose()
On Error Resume Next
With Sheets("SplashPage")
.Visible = xlSheetVisible
.Activate
End With
Sheets("Plan1").Visible = xlSheetVeryHidden
Sheets("Users").Visible = xlSheetVeryHidden
ThisWorkbook.Save
End Sub
Since our close routine makes changes to the workbook to hide sensitive information, those changes need to be saved. If ThisWorkbook.Save wasn't there, Excel would prompt the user if they wanted to save "their" changes. Which is annoying at best, confusing at worst, because most users will have already pressed "Save" before closing. And if we give them the option here now to close without saving, then we run the risk of all those sensitive worksheets we've just made xlVeryHidden visible to the next user. And that next user could be a bad guy who knows how to disable macros (or anyuser who simply has macro security set above Medium) which means that the following code wouldn't run:
Private Sub Workbook_Open()
On Error Resume Next
Sheets("Users").Range("D1").Value = 3
With Sheets("SplashPage")
.Visible = xlSheetVisible
.Activate
End With
Sheets("Plan1").Visible = xlSheetVeryHidden
Sheets("Users").Visible = xlSheetVeryHidden
ThisWorkbook.Save
frmLogin.Show
End Sub
which is my semi-paranoid-self trying to make it as sure as possible that the next user opening this file doesn't see something I don't want them to.
Note that none of this secuity is bomb-proof. It will lock out most average Excel users that you don't want in it, but someone who knows more about VBA than I do could probably find a way in.
Yes, that was an invitation. :)
I have an Excel sheet which has fields to enter data.
Let's say the total fields is 20. Ten of them are locked by default whenever the user opens the workbook. Now, one of the fields is asking the user to enter a password. If the password was "AAA", then five fields (of the ten locked ones) will be unlocked . If the user inputs a password as "BBB", then all the cells of the worksheet will be read-only and locked.
I am focusing on the case when the user inputs "BBB". I tried this code:
if Range("Password").value="BBB" then
cells.select
selection.locked=true
end if
It gives me an error as " Overflow".
If Range("Password").Value = "BBB" Then
ActiveSheet.UsedRange.Locked = True
End If
It gives me an error as " Overflow".
I doubt you should get an overflow error with this code. An overflow may occur if you use something like Cells.Count in Excel 2007 onwards. CountLarge was introduced just because Cells.Count returns an Integer value which errors out in Excel 2007 because of increased rows/columns. Cells.CountLarge returns a Long value.
Now back to your query.
You do not need to SELECT all cells. In fact you should avoid the use of Select. You may want to see How to avoid using Select in Excel VBA
Also locking all the cells of the worksheet will be ineffective if you do not protect your worksheet. You can change your code to
If Range("Password").Value = "BBB" Then
With ActiveSheet
.Cells.Locked = True
.Protect "Password"
End With
End If
And if you do not want to use Activesheet then use something like this
Option Explicit
Sub Sample()
Dim ws As Worksheet
'~~> Change this to the relevant sheet
Set ws = Sheet1
With ws
If .Range("Password").Value = "BBB" Then
.Cells.Locked = True
.Protect "Password"
'~~> To unprotect, uncomment the below
'.UnProtect "Password"
End If
End With
End Sub