Uncheck "Checkboxes" in Excel - excel

I have the following code to uncheck all the Checkboxes in sheet.
It doesn't change the boxes. I get the message box confirming that the range is green and therefore the loop should kick in.
Sub Changeboxes()
'Dim cb As CheckBox'
If Sheet1.Range("a1").Value = "green" Then
MsgBox "The range is green.", vbOKOnly
For Each cb In Sheet1.CheckBoxes
cb.Value = True
Next cb
Else
MsgBox "The range is NOT green.", vbOKOnly
End If
MsgBox "Checked availability updated.", vbOKOnly
End Sub

Change this line : cb.Value = True to cb.Value = False to uncheck the boxes.
EDIT
Yes, if the checkboxes are activex objects then the above code will not work. Instead, use the following code:
Sub ChangeBoxes()
Dim obj As OLEObject
If Sheet1.Range("a1").Value = "green" Then
MsgBox "The range is green.", vbOKOnly
For Each obj In Sheet1.OLEObjects
obj.Object.Value = True
Next
MsgBox "Checked availability updated.", vbOKOnly
Else
MsgBox "The range is NOT green.", vbOKOnly
End If
End Sub
I have also moved the last messagebox into the first part of the if statement because it was popping up whether or not the value in A1 was green.

Related

How to use a variable with a Property After

This should be simple. I am working with userforms. I want to save a number that is stored in a cell and concatenate it with "lbl" and store it in a variable called Label. This works. I Then need to use the property .Caption but get a 424 error. Replacing the variable with what is stored in it ("lbl1"), the code runs.
Not sure why this is not working. Any help appreciated.
Sub ErrorExample()
Dim Label As String
'Clear previous click
If Worksheets("BackEnd").Range("D2").Value = "" Then
'No previous click
Else
'This does not work
Label = "lbl" & Worksheets("BackEnd").Range("D2").Value
With Label
'Clear previous click
.Caption = ""
End With
'This works
With lbl2
'Clear previous click
.Caption = ""
End With
End If
End Sub
Userform: Reference a Control By Its Name
Copy the code into the user form's module.
Private Sub ToClearOrNotToClear()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("BackEnd")
Dim Label As String: Label = CStr(ws.Range("D2").Value)
Dim lbl As Control
If Len(Label) > 0 Then
On Error Resume Next
Set lbl = Controls("lbl" & Label)
On Error GoTo 0
If lbl Is Nothing Then
MsgBox "Label not found!", vbCritical
Exit Sub
End If
If Len(CStr(lbl.Caption)) = 0 Then
MsgBox "Label is clear!", vbExclamation
Exit Sub
End If
lbl.Caption = ""
MsgBox "Label cleared.", vbInformation
End If
End Sub

How to edit data from a form in a sheet to another form with the Data using VBA?

ive been learning VBA and Excel in the past 2 weeks by my own during my free time, but sometimes we need some help, and currently ive no one to help besides the internet. So ive developed a Form(Sheet1) in a sheet using shapes and excel cells so the user could perform operations like insert,update, new register to the other sheet(Data) which is my Data Sheet or DataTable more specifically. But im struggling to get the update button to work. i could definitely use some help.
Heres my code:
Public Upda As String
Sub Search()
'
' Search Macro
'
Dim Sheet As String, ans
On Error GoTo Erro:
Data.Activate
Sheet = Data.Name
ans = InputBox("Write down the ID", "Search")
If ans = "" Then
Sheet1.Activate
Exit Sub
End If
Dim C
With Worksheets(Data).Range("A:A")
Set C = .Find(ans, LookIn:=xlValues, lookat:=xlWhole)
If Not C Is Nothing Then
C.Activate
Sheet1.Cells(17, 9).Value = C.Value ' Id
Sheet1.Cells(9, 4).Value = C.Offset(0, 1).Value ' Name
' here goes the other fields to be inserted
Sheet1.Activate
Upda = Sheet1.Cells(17, 9).Text
Else
Sheet1.Activate
MsgBox "Insert a valid ID", vbCritical, "Search"
End If
End With
Exit Sub
Erro:
MsgBox "Something went wrong, contact the Adm!", vbCritical, "Erro"
End Sub
'Update macro need to get a fix
Sub Update()
'update macro
Dim Sheet As String
On Error GoTo Erro
If IsEmpty(Range("I17")) Or IsEmpty(Range("D9")) Then ' there are more fields to validate
MsgBox "All the fields must have a value", vbExclamation, "Upda"
If Upda = "" Then
MsgBox "Please retry the search", vbExclamation, "Update"
Exit Sub
End If
Dim C
'
Data.Activate
Sheet = Data.Name
With Worksheets(Sheet).Range("A:A")
Set C = .Find(Upda, LookIn:=xlValues, lookat:=xlWhole)
If Not C Is Nothing Then
C.Activate
ActiveCell.Value = Sheet1.Cells(17, 9).Text ' ID
ActiveCell.Offset(0, 1).Value = Sheet1.Cells(9, 4).Text ' Name
'Update the table with the contents of the form1
Sheet1.Activate
Range("I6:J6").ClearContents
' remaining code to clear the contents of the form sheet1
Upda = ""
'Call clear
Else
MsgBox "ID number not found", vcCritical, "Update"
End If
End With
Exit Sub
Erro:
MsgBox "Something went wrong, contact the Adm!", vbCritical, "ERRO"
End Sub
Sub clear()
'
' clear Macro
'
Range("I17").ClearContents
' remaining code to cleear the contents of the form sheet1
Upda = ""
End Sub
Each one of those macros are associated with a Button(Shape), evrything is working besides the Update one.
Im getting the follow error which makes no sense to me
PS:if u need more information please let me know
You are missing the End if statement for the first If in the below block of code:
If IsEmpty(Range("I17")) Or IsEmpty(Range("D9")) Then ' there are more fields to validate
MsgBox "All the fields must have a value", vbExclamation, "Upda"
End if 'Missing If in the original code
If Upda = "" Then
MsgBox "Please retry the search", vbExclamation, "Update"
Exit Sub
End If

VBA unprotect-blank entry and exit handling [duplicate]

This question already has an answer here:
How to handle the InputBox cancel button?
(1 answer)
Closed 1 year ago.
The below code unprotects all sheets in the workbook and prompts for the password only once.
What I am trying to achieve is:
If user presses "cancel" on the password input window, the sub exits.
If user presses "ok" without entering anything, it should behave in the same way as entering the wrong password i.e. go to the error popup.
The issue is on pressing "ok" or "cancel" it doesnt behave as above, rather, in both cases, it brings up the default password prompt 3 more times, 1 for each sheet.
I am struggling with perfecting the if/then logic and have swapped things around many times, almost getting there but never quite.
Sub UnprotectAllSheets()
Dim ws As Worksheet
Dim pass As String
If ActiveSheet.ProtectContents = False Then
MsgBox "Already Unprotected"
Exit Sub
Else
pass = InputBox("Password?")
On Error GoTo Popup:
For Each ws In ThisWorkbook.Worksheets
ws.Unprotect pass
Next ws
If ActiveSheet.ProtectContents = False Then
MsgBox "Sheets now Unprotected"
ElseIf StrPtr(pass) = "" Then 'if press OK on blank entry
MsgBox "Incorrect Password", vbCritical, "Admin"
ElseIf pass = 0 Then 'if press CANCEL
Exit Sub
End If
End If
Popup:
If err.Number = 1004 Then
MsgBox "Incorrect Password", vbCritical, "Admin"
End If
End Sub
InputBox behaves similarly for cases of pressing Cancel, inputting an empty string or pressing window corner x, in terms of String return.
The next sub gives a possibility to separate the above cases:
Sub testInputBox()
Dim pass
pass = InputBox("Password?")
'standard behavior without checking the result:
MsgBox "Pass is " & pass 'it will be an empty string in case of Cancel, empty string, pressing window corner X
If StrPtr(pass) = 0 Then
MsgBox ("Cancel pressed...") 'the same message if window corner `X` is pressed
ElseIf pass = vbNullString Then
MsgBox ("Empty string..") 'OK for an empty string
Else
MsgBox ("You entered " & pass)
End If
End Sub
No need of error handling if you use the above way of identification.
And I should modify your code to act in this way:
Sub UnprotectAllSheets()
Dim ws As Worksheet, pass As String, myPass As String, i As Long
myPass = "1234"
TryAgain:
pass = InputBox("Password?")
If StrPtr(pass) = 0 Then Exit Sub 'for Cancel and window corner 'X' pressed
If pass = vbNullString Then MsgBox "You did not enter any password!", vbCritical, "Admin": Exit Sub
If pass <> myPass Then
MsgBox "Incorrect Password" & vbCrLf & _
IIf(i < 3, "Please, try again!", "We stop here..."), vbCritical, "Admin"
If i >= 3 Then Exit Sub
i = i + 1
GoTo TryAgain
End If
For Each ws In ThisWorkbook.Worksheets
If ws.ProtectContents = True Then
ws.Unprotect pass
End If
Next ws
End Sub

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

excel vba - check if radio button is selected?

I'm trying to check the value of these simple radio button groups but my syntax is off, does anyone know what to change?
Note: they are Excel Option Buttons not ActiveX ones and they are not on a userform.
If Worksheets("Input").Shapes("Option Button 3").Select.Value = xlOn Then
MsgBox "fir"
ElseIf Worksheets("Input").Shapes("Option Button 4").Select.Value = xlOn Then
MsgBox "sec"
Else
MsgBox "none" 'in case they were deleted off the sheet
End If
Try this
Sub ZX()
Dim shp3 As Shape
Dim shp4 As Shape
On Error Resume Next
Set shp3 = Worksheets("Input").Shapes("Option Button 3")
Set shp4 = Worksheets("Input").Shapes("Option Button 4")
On Error Goto 0
If shp3 Is Nothing Then
If shp4 Is Nothing Then
MsgBox "none" 'in case they were deleted off the sheet
ElseIf shp4.ControlFormat.Value = xlOn Then
MsgBox "sec"
Else
MsgBox "Only Button 4 exists and it is off"
End If
Else
If shp3.ControlFormat.Value = xlOn Then
MsgBox "fir"
Else
If shp4 Is Nothing Then
MsgBox "Only Button 3 exists and it is off"
ElseIf shp4.ControlFormat.Value = xlOn Then
MsgBox "sec"
Else
MsgBox "Both exists, both are off"
End If
End If
End If
End Sub
I had a similar problem. To solve it, I decided to use a toggle button with this macro VBA code to access its value and toggle my display accordingly to it:
Call ThisWorkbook.Sheets("MySheet").toggleDisplay(CBool(ThisWorkbook.Sheets("MySheet").ToggleButton1.Value))

Resources