The Input Box keeps popping up in excel - excel

I am trying to type code in VBA where a macro button pops up based on a cell value and the password typed after a cell has that specific value. It works for the most part, but the Input Box keeps popping up after I have typed the password. Whenever I click on another cell or type something in a different cell, the input box keeps popping up after I've typed the password for admin. I am not sure why it does that.
Sub enable_()
Application.EnableEvents = True
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
'If user is selected, hide button. If admin is selected, enter password to see the button'
If Range("A5") = "User" Then ActiveSheet.CommandButton1.Visible = False
If Range("A5") = "Admin" Then
strwork = InputBox("Please enter Admin Password.")
If strwork = "excel" Then ActiveSheet.CommandButton1.Visible = True
End If
End Sub

Worksheet Change feat. InputBox
Application.Intersect method
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
' If user is selected, hide button.
' If admin is selected, enter password to see the button'
Dim sCell As Range: Set sCell = Me.Range("A5")
If Intersect(Target, sCell) Is Nothing Then Exit Sub
With Me.CommandButton1
Select Case sCell.Value
Case "User"
If .Visible Then .Visible = False
Case "Admin"
Dim pWord As String
pWord = InputBox("Please enter Admin Password.")
'If .Visible Then .Visible = False
If pWord = "excel" Then
If Not .Visible Then .Visible = True
End If
End Select
End With
End Sub

Related

Code only works when I click on a cell in the sheet?

I used checkboxes, when clicked depending on which checkbox is selected, specific rows unhide.
Code runs fine. Only issue is that code is not triggered by clicking the checkbox but works when I select any cell in the sheet.
Below is some of the code used:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveSheet.Activate
If Range("C2").Value Or Range("C3").Value Or Range("C4").Value Or Range("C5").Value Or Range("C6").Value Or Range("C7").Value Or Range("C8").Value Or Range("C9").Value Then
Rows("39:52").EntireRow.Hidden = False
Rows("166:169").EntireRow.Hidden = False
Rows("173:175").EntireRow.Hidden = False
Else
Rows("39:52").EntireRow.Hidden = True
Rows("166:169").EntireRow.Hidden = True
Rows("173:175").EntireRow.Hidden = True
End If
End Sub
Because you using event [Worksheet_SelectionChange], so it only run when you change selection cell.
If you want run when you click checkbox, you must write event [click] of checkbox
Ex:
Sub CheckBox1_Click()
End Sub

how to retrieve a value from an userform

I'm trying to write a code to trace every change made by the user on any worksheet. The user will input data and from time to time will erase said data and/or correct the original value they inserted. If the change is either deletion or modification, an Userform will pop up and the user will include a reason for that change. Right now I'm able to display the form everytime the user makes one of the changes mentioned before, but I'm not able to retrieve the reason, could you guys help me?
This is what I have for the UserForm
Private Sub CommandButton1_Click()
Dim msgvalue As VbMsgBoxResult
Dim value As String
msgvalue = MsgBox("Do you wish to save the change?", vbYesNo + vbInformation, "Confirm")
If msgvalue = vbNo Then GoTo Command
If msgvalue = vbYes Then
value = UserForm1.txtCmmt.Value
If value = "" Then GoTo Command
End
End If
Command:
MsgBox ("A reason must be provided")
With UserForm1
.txtCmmt.Value = ""
End With
End Sub
So if a user tries to delete a value, the code is the following:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim sLastAction As String
Dim Cell As Range
sLastAction = Application.CommandBars("Standard").Controls("&Undo").List(1)
For Each Cell In Target
If sLastAction = "Clear" Or sLastAction = "Delete" Or Left(sLastAction, 9) = "Typing ''" Then
UserForm1.Show 'this is where I'm stuck, I'm not sure how to retrieve the value from the form
End If
'the code continues to retrieve other info from the changes made, including the "reason"
Thanks for the help!
Try the next way, please:
Let us say that your text box where the comment will be written is named "txtComment".
Put this code in its Exit event:
Private Sub txtComment_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Me.txtComment.text <> "" Then
If ActiveSheet.Name <> "LogDetails" Then
Application.EnableEvents = False
Sheets("LogDetails").Range("A" & rows.count).End(xlUp).Offset(0, 5).Value = Me.txtComment.text
Application.EnableEvents = True
Unload Me
End If
End If
End Sub
Let the existing Worksheet_Change event as it is, only launching the form and maybe making a Public boolean variable (from a standard module) True (something boolStop) which will not allow changing anything in any worksheet until it is not False.
Then fill the text you need in the text box ("txtComment", or however you named it) and press Enter. If my above suggestion looks interesting for you, the last line of the text box event will be boolStop = False.
If you understand how to implement the above simple solution, you maybe will forget about a user form and use a simple InputBox, as in the next example:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address(0, 0) <> "E1" Then Exit Sub
Dim sLastAction As String, comValue As String
Dim Cell As Range
sLastAction = Application.CommandBars("Standard").Controls("&Undo").list(1)
For Each Cell In Target
If sLastAction = "Clear" Or sLastAction = "Delete" Or left(sLastAction, 9) = "Typing ''" Then
WritePlease:
comValue = InputBox("Please write the reason for cell """ & Cell.Address & """ (" & sLastAction & ").", "Reason, please")
If comValue = "" Then GoTo WritePlease
If ActiveSheet.Name <> "LogDetails" Then
Application.EnableEvents = False
'Stop
Sheets("LogDetails").Range("A" & rows.count).End(xlUp).Offset(0, 5).Value = comValue
Application.EnableEvents = True
End If
End If
Next
End Sub

Access password blocked sheet - Excel

The code below restricts access by hiding a sheet unless a password is entered. If it is entered correctly, the sheet can be viewed from the individual tabs. However, it won't let me view and then edit the sheet.
Can this be adjusted to allow the user to enter a password and then view and edit the sheet?
Private Sub Workbook_Open()
Sheets("Sheet1").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
Application.EnableEvents = True
ViewAccess = True
End If
End If
End Sub
Following code will help you. When a user will select a sheet with name HiddenSheet it will ask for password. If password is correct then it will allow for editing data otherwise will go to previous sheet automatically, You have to change HiddenSheet for your sheet name.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheetName As String
MySheetName = "HiddenSheet" 'The sheed which I want to hide.
If Application.ActiveSheet.Name = MySheetName Then
Application.EnableEvents = False
Application.ActiveSheet.Visible = False
response = Application.InputBox("Password", "Enter Password", "", Type:=2)
If response = "123456" Then 'Unhide Password.
Application.Sheets(MySheetName).Visible = True
Application.Sheets(MySheetName).Select
End If
End If
Application.Sheets(MySheetName).Visible = True
Application.EnableEvents = True
End Sub
Code snipped:

How to detect if user select cancel InputBox VBA Excel

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

Make checkboes visible and invisible when a checkbox is ticked and unticked

Heres the Code that I put in the module1 from Tim Williams
Sub Tester()
Dim isOn As Boolean
With ActiveSheet
Application.Caller = MuddyBoots
isOn = (.CheckBoxes(Application.Caller).Value = xlOn)
.CheckBoxes("TabletUser").Visible = isOn
.CheckBoxes("WebUser").Visible = isOn
End With
End Sub
I have three checkboxes:
MuddyBoots
TabletUser
WebUser
When MuddyBoots is ticked I want TabletUser and WebUser to be visible and when MuddyBoots is unticked I want the two checkboxes TabletUser and WebUser to be invisible.
The code that works-ish is below:
Public Sub TestCheckbox()
Dim s As Shape
Set s = ActiveSheet.Shapes("MuddyBoots")
s.Select
If Selection.Value = xlOn Then
MsgBox "Checked"
ActiveSheet.CheckBoxes("TabletUser").Visible = True
ActiveSheet.CheckBoxes("WebUser").Visible = True
'code here
Else
MsgBox "Not checked"
ActiveSheet.CheckBoxes("WebUser").Visible = False
ActiveSheet.CheckBoxes("TabletUser").Visible = False
'code here
End If
End Sub
This removes the two checkboxes if MuddyBoots is unticked after you ok the pop up message. If I comment out the msgbox line it doesn't work. Then I have to restart the VBA code.
These are form controls.
I also get the error message: Cannot run the macro New User Form Macro'!CheckBox17_Click'. The macro may not be available in this workbook or all macros may be disabled. I have changed the name of the checkboxs in the name box and have triple checked the checkboxes and they have the correct names...
I want to know how to get this functionality working without the popup messages and without the error please.
Sub Tester()
Dim isOn As Boolean
With ActiveSheet
'Application.Caller = name of calling shape
isOn = (.CheckBoxes(Application.Caller).Value = xlOn)
.CheckBoxes("TabletUser").Visible = isOn
.CheckBoxes("WebUser").Visible = isOn
End With
End Sub

Resources