I've used the 'protection worksheet' option in Excel but in addition, I 'd like to ask the user to input a password upon clicking on each sheet. There's a specific password per sheet. If you don't know the password, I don't want the user to be able to modify anything on the sheet. They can print but can't modify anything. I have a password per sheet but the code I'm using isn't working...Maybe it's too basic...Can someone please assist?
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim Msg As String
Dim UserEntry As Variant
Msg = InputBox("What is the password?")
Do
Sheet1.Activate
UserEntry = InputBox(Msg)
If UserEntry = "test" Then Exit Sub
If UserEntry = False Then
Msg = "Invalid Password!"
Msg = Msg & vbNewLine
Msg = Msg & "What is the password?"
Loop
Sheet1.Activate = UserEntry
End Sub
Although it might depend on your version of Excel (I tested in 2007), just right-click the tab and select "Protect Sheet". You can set a password for each sheet seperately.
A user will just go to the Review tab in the ribbon and select "Unprotect sheet" and enter the password.
You really want to avoid setting passwords via VBA since it's really easy to go into the code to find the password.
Here's the basics, you can add back the check for an invalid password.
Private Sub Worksheet_Activate()
Dim Msg As String
Dim UserEntry As String
Msg = InputBox("What is the password?")
If Msg = "test" Then
ActiveSheet.Unprotect ("password")
End If
End Sub
try this in ThisWorkbook module
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
On Error GoTo WrongPassword
Sh.Unprotect
CleanUp:
Exit Sub
WrongPassword:
MsgBox "Wrong Password"
End Sub
Related
I am working on a userform that inserts data into a DB. There is a modify button that allows to update data but I want allow confirmation of update with a password. Therefore, in the Code of the modify button, I am calling another userform that prompts the user to enter a password. The problem I am having is that I have created a boolean variable that is set to True when the password is correct and to False other. When the password is correct, the code for the modify button continues but the True info is not transmitted to the first userform
I have seen a lot of similar questions here but none of the answers that I have seen has helped me solve my problem. I have created some public variables in both codes but still does not work
Here is the code for the modify button (First userform)
Private Sub modify_Click()
On Error GoTo handler
Dim connec As Object
Dim rst As Object
Dim stringconn As String
Dim sqlupdt As String
Dim modifmat As String
Dim msg
--Some code here
if [condition] then
goto 1
end if
1 password.show
if pwcorr= True then
goto 2
else
msgbox "Incorrect password"
exit sub
end if
3 --Some code here
end sub
and here is the code for the password userform (2nd userform)
Public pwcorr
public sub OkBtn_Click()
Dim pw As String
Dim pwin As String
Dim pwcorr As Boolean
pw= "abcde"
pwin = Me.pwin.Text
If pwin = vbNullString Then
MsgBox "No password was entered", vbCritical
ElseIf pwin = pw Then
Me.pwcorr = True
Unload Me
Else
MsgBox "Password incorrect", vbCritical
End If
End Sub
Whenever I get to the point where I check If pwcorr = True in the first code, the pwcorr is always empty. Don't know why
I'm making an InputBox so the user can put his/her name to be used for the MsgBox. Instead of "hello user", it would be "hello (name)". This was my attempt.
Private Username As String
Username = InputBox(msg, "dear user")
InputBox msg, "dear user"
If Username = vbNullString Then
Username = InputBox(msg, "dear user")
End If
I tried first making the inputbox (which is working).
Private Sub Workbook_open()
Worksheets("Sheet1").Select
Dim msg
msg = "Please enter your name here"
InputBox msg, "dear user"
End Sub
Welcome to Stackoverflow.
Is this what you are trying?
Sub Sample()
Dim Ret As Variant
Ret = InputBox("Please enter your name", "dear user")
If Len(Trim(Ret)) <> 0 Then MsgBox "Hello " & Ret
End Sub
I tried using urcode, but it doesnt seem to work? i tried placing it in the sheet, module, & workbook but nothing is happening D: and oh yea, my aim is to use the input of the inputbox for all the msgboxes im going to use in all my sheets, say first, if the file opens, it asks for the name of the user; after typing the name, there is a msgbox saying "welcome to the game"(or something like that) then there are different sheets for my games like roll the dice, maze, etc. so when the user goes to the sheet, it welcomes them again via msgbox and congratulates them when the game has been finished – Kurt Cinco 31 mins ago
In such a case you should not use a public variable. The variable resets when there is an error. I would recommend saving that name to a cell in a hidden sheet.
A. Add a sheet call say Settings. Hide the sheet.
B. In the workbook open, paste this code
Private Sub Workbook_Open()
Dim Ret As Variant
Ret = InputBox("Please enter your name", "dear user")
If Len(Trim(Ret)) <> 0 Then
ThisWorkbook.Sheets("Settings").Range("A1").Value = Ret
MsgBox "welcome to the game " & Ret
End If
End Sub
C: In the sheet code are you can use this code
Sub Sample()
Dim username As String
username = ThisWorkbook.Sheets("Settings").Range("A1").Value
MsgBox "Hello " & username
End Sub
you can set a ThisWorkbook object property
place this code in ThisWorkbook code pane:
Option Explicit
Private mUserName As String
Sub Workbook_Open()
mUserName = InputBox("Please enter your name", "dear user")
End Sub
Public Property Get MyUserName() As String
MyUserName = mUserName
End Property
now you can access from any plain module and/or sheet module by simply coding
MsgBox "hello " & ThisWorkbook.MyUserName
as a possible enhancement, you could force the user to put some valid name by properly tweaking Workbook_Open() sub, like:
Sub Workbook_Open()
Do
mUserName = InputBox("Please enter your name", "dear user")
Loop While mUserName = vbNullString
End Sub
I've got a very large and somewhat fragile spreadsheet that I'm working on, and I'd like to limit access to more complicated macros--ones that delete or add data. I'm less worried about security than I am about someone who doesn't know what they're doing deleting unfortunate things. I've used the 'inputbox' password trick, but it becomes slightly annoying to have to keep putting in the password over and over. Is there any way to have the macro 'remember' that I put in the password once, and then reset after I close the sheet, without storing it in a cell somewhere?
Here's the code I'm currently using:
Sub ControlPanel()
Dim PassProtect As Variant
PassProtect = InputBox(Prompt:="Please enter the password to unlock the updater." & vbCrLf & "(Case Sensitive)", Title:="Control Panel")
If PassProtect = vbNullString Then Exit Sub
If PassProtect = "password" Then
ControlPanelForm.Show vbModeless
Else: MsgBox Prompt:="Incorrect password. Please try again.", Buttons:=vbOKOnly
End If
End Sub
Thanks!
You can use a public variable to store a value when the workbook is open, so the code would become:
Public pblnEnteredPassword As Boolean
Sub ControlPanel()
Dim PassProtect As Variant
If pblnEnteredPassword Then GoTo DoStuff
PassProtect = InputBox(Prompt:="Please enter the password to unlock the updater." & vbCrLf & "(Case Sensitive)", Title:="Control Panel")
If PassProtect = vbNullString Then Exit Sub
If PassProtect = "password" Then
pblnEnteredPassword = True
GoTo DoStuff
Else
MsgBox Prompt:="Incorrect password. Please try again.", Buttons:=vbOKOnly
Exit Sub
End If
DoStuff:
ControlPanelForm.Show vbModeless
End Sub
Use a static string var within the CommandButton1_Click sub procedure. Once entered correctly, it will be 'remembered' for the duration of the session.
Option Explicit
Private Sub CommandButton1_Click()
Static pwd As String
try_again:
If pwd <> "thePassword" Then
'password challenge
pwd = InputBox(Prompt:="Please enter the password to unlock the updater." & vbLf & "(Case Sensitive)", _
Title:="Control Panel")
'check if the password challenge was cancelled
If pwd = vbNullString Then Exit Sub
'compare again
GoTo try_again
End If
'all the good code once the password challenge has been passed
Debug.Print "pass"
End Sub
I have an input box asking user to enter a date. How do I let the program know to stop if the user click cancel or close the input dialog instead of press okay.
Something like
if str=vbCancel then exit sub
Currently, user can hit OK or Cancel but the program still runs
str = InputBox(Prompt:="Enter Date MM/DD/YYY", _
Title:="Date Confirmation", Default:=Date)
If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...
EDIT to properly differentiate between empty string and cancel, according to this answer.
Your example
Private Sub test()
Dim result As String
result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
If StrPtr(result) = 0 Then
MsgBox ("User canceled!")
ElseIf result = vbNullString Then
MsgBox ("User didn't enter anything!")
Else
MsgBox ("User entered " & result)
End If
End Sub
Would tell the user they canceled when they delete the default string, or they click cancel.
See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx
Following example uses InputBox method to validate user entry to unhide sheets:
Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.
Sub unhidesheet()
Dim ws As Worksheet
Dim pw As String
pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then
Exit Sub
ElseIf pw = NullString Then
Exit Sub
ElseIf pw = 123456 Then
For Each ws In ThisWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next
End If
End Sub
The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.
For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:
Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then 'I also tried with sRange.address and vbNullString
MsgBox ("Cancel pressed!")
Exit Sub
End If
MsgBox ("Your custom range is " & sRange.Address)
End Sub
The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:
Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
MsgBox ("Cancel pressed")
End Sub
So, the question is how to detect either an error or StrPtr()=0 with an If statement?
If your input box is an array, it does not work. I have solved it by adding a check for if it is an array first.
Dim MyArrayCheck As String
Dim MyPlateMapArray as variant
MyPlateMapArray = Application.InputBox("Select ....", Type:=8)
MyArrayCheck = IsArray(MyPlateMapArray)
If MyArrayCheck = "False" Then
Exit Sub
End If
I have solved it with a False like below
MyLLOQ = Application.InputBox("Type the LLOQ number...", Title:="LLOQ to be inserted in colored cells.", Type:=1)
If MyLLOQ = False Then Exit Sub
If user click cancel the sub will exit.
Another suggestion.
Create a message box when inputbox return null value. Example:
Dim PrC as string = MsgBox( _
"No data provided, do you want to cancel?", vbYesNo+vbQuestion, "Cancel?")
Sub TestInputBox()
Dim text As String
text = InputBox("Type some text")
If text = "" Then
MsgBox "button cancel pressed or nothing typed"
Else
MsgBox text
End If
End Sub
Inputbox send a boolean False value when Cancel is pressed.
contenidoy = Application.InputBox("Cantidad = ", titulox, contenidox, , , , , Type:=1)
'ESC or CANCEL
If contenidoy = False Then
MsgBox "Cancelado"
Else
MsgBox "Edición aceptada"
'End If
I have been trying to create this password protection type thing in excel VBA for Applied ICT project. So I have created this module which protects all the sheet in the work books:
Public Sub Auto_Open()
Dim ws As Worksheet
Dim psword As String
psword = "Unit 12"
For Each ws In Worksheets
ws.Protect Password:=psword
Next ws
End Sub
Now the thing that i want to do is that whenever someone will open an userform an inputbox asking for the password will appear and if someone enters an invalid password a message box would appear. It will be something like this:
Private Sub UserForm_Activate()
If ActiveSheet.ProtectContents = True Then
x = InputBox("Please type in the password", "Password")
If x = psword Then
Call Module1.Sheets_unlock
Else
Msgbox("The password is invalid")
End
End If
End If
Now the problem is the of password changes to nothing in the UserForm_Activate() sub. I have tried the public psword as string, but it doesn't work. What can i do?
Its where you Dim it.
Dim psword in a standard module above all other subs in the module like:
Public psword As String