Select / unselect all CheckBoxes in a range EXCEL VBA macro - vba

I am creating a VBA macro to select all checkboxes in a sheet and it works fine but now i want to adjust my code to select and unselect just the checkboxes in a particular range.
Here is my code.
Sub Select_all()
Dim Cbox As CheckBox
Dim Rng As Range
Set Rng = ActiveWorkbook.Sheets("Sheet4").Range("B7, B104")
For Each Cbox In ActiveSheet.CheckBoxes
If Not Intersect(Cbox.TopLeftCell, Rng) Is Nothing Then
If Cbox.name <> ActiveSheet.CheckBoxes("Check Box 104").name Then
Cbox.Value = ActiveSheet.CheckBoxes("Check Box 104").Value
End If
End If
Next Cbox
End Sub
I added
If Not Intersect(Cbox.TopLeftCell, Rng) Is Nothing
but it doesn't change anything, and when i remove this part then it selects all the checkboxes in the sheet and i need only for the Range("B7:B104")
Any suggestions please ? Thank you very much.

This works for me. But I changed the cb# to "1" because I don't have 104 of them on my test sheet. Any cb's in range B7:B104 will be changed to the value of cb1, which you can change to cb104 in your script.
Sub Link_Checkboxes_To_Cells()
Dim cBox As CheckBox
For Each cBox In Sheet1.CheckBoxes
If Not Intersect(cBox.TopLeftCell, Range("B7:B104")) Is Nothing Then
If cBox.Name <> ActiveSheet.CheckBoxes("Check Box 1").Name Then
cBox.Value = ActiveSheet.CheckBoxes("Check Box 1").Value
End If
End If
Next cBox
End Sub

#JuniorDev
There are a few reasons why the above code doesn't work for you. I'll try to list them.
The above code works for "Form Control" checkboxes - Not ActiveX type checkboxes. You would need a different code for ActiveX checkboxes. Or you may not have a form checkbox named "Check Box 1". But I think that would give you an error. Or your other checkboxes may not be in the Range("B7:B104"). You can try changing that to Range("A1:Z10000") to insure your checkboxes are in the range.
If you are not sure what type checkboxes you have then you can run the following code to find their names and what type of control they are, either form or activex. It will print the info in your immediate window of the VB editor.
Sub CheckboxLoop()
'PARTIAL SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim cb As Shape
'Loop through Form Checkboxes
For Each cb In ActiveSheet.Shapes
If cb.Type = msoFormControl Then
If cb.FormControlType = xlCheckBox Then
Debug.Print "Form Control: " & cb.Name
End If
End If
Next cb
'Loop through ActiveX Checkboxes
Dim ChkBx As OLEObject
For Each ChkBx In ActiveSheet.OLEObjects
If TypeName(ChkBx.Object) = "CheckBox" Then
Debug.Print "ActiveX Control: " & ChkBx.Name
End If
Next ChkBx
End Sub

Sorry to resurrect an old post, but I hate it when a solution has not been provided and I know the answer, which is seldom. Thank you, this helped me on a project I am currently working on.
If you're like me, I change all my Sheet Names for sake of clarity.
For Each cBox In Sheet1.CheckBoxes
This line in John Muggins code limits you to the Sheet Name, "Sheet1".
I was able to change the line to...
For Each cBox In ActiveSheet.CheckBoxes
...and it worked perfectly.

Related

How to add a macro to mutiple excel files using VBA

Is there any way to write a VBA Macro to input another VBA Macro into multiple excel workbooks? If so, how do I start?
Any and all help is greatly appreciated.
you'll need a reference first
Microsoft Visual Basic For Applications Extensibility 5.3
And here you go. Have fun
Public Sub AddNewModule()
Dim proj As VBIDE.VBProject
Dim comp As VBIDE.VBComponent
Set proj = ActiveWorkbook.VBProject
Set comp = proj.VBComponents.Add(vbext_ct_StdModule)
comp.Name = "MyNewModule"
Set codeMod = comp.CodeModule
With codeMod
lineNum = .CountOfLines + 1
.InsertLines lineNum, "Public Sub ANewSub()"
lineNum = lineNum + 1
.InsertLines lineNum, " MsgBox " & """" & "I added a module!" & """"
lineNum = lineNum + 1
.InsertLines lineNum, "End Sub"
End With
End Sub
You can also just use the workbook with the code in it as a reference as well. Then you can call the module remotely.
As #BruceWayne mentioned, there is also sotring it in the personal book.
tl;dr - there's a few options that can get you there.
I recommend storing them in the Personal.xslb file which is accessible across Excel.
See this page or this page for more detail, but generally a quick way to get started is:
Press ALT+F11 to open the VBEditor.
Right click the "VBAProject (PERSONAL.XLSB)" and Add a new module
Add your code in the module.
Now, when you go to View --> Macros, you can choose to see those stored in the Personal.xlsb file:
(I "whited out" my macros for privacy, but they'll be listed by name)
Note: If you do not have a "Personal.xlsb", then you must create it. Simply record a new macro, but choose to store it in "Personal Macro Workbook". Then you should see it in the VBEditor.
I would think the easiest way to have the same code in slightly different Excel files is to have one 'template' and save it several times as several slightly different files. Or, if you want to get fancy, you can create an AddIn to make an Excel Macro available to all workbooks.
Option Explicit
Dim cControl As CommandBarButton
Private Sub Workbook_AddinInstall()
On Error Resume Next 'Just in case
'Delete any existing menu item that may have been left.
Application.CommandBars("Worksheet Menu Bar").Controls("Super Code").Delete
'Add the new menu item and Set a CommandBarButton Variable to it
Set cControl = Application.CommandBars("Worksheet Menu Bar").Controls.Add
'Work with the Variable
With cControl
.Caption = "Super Code"
.Style = msoButtonCaption
.OnAction = "MyGreatMacro"
'Macro stored in a Standard Module
End With
On Error GoTo 0
End Sub
Private Sub Workbook_AddinUninstall()
On Error Resume Next 'In case it has already gone.
Application.CommandBars("Worksheet Menu Bar").Controls("Super Code").Delete
On Error GoTo 0
End Sub
This code will be all you need to add a single menu item (called Super Code) to the end of the existing Worksheet Menu Bar as soon as the Add-in is installed by the user via Tools>Add-ins. When the Super Code menu item is clicked a macro (that is within a standard module of the add-in) is run. As mentioned earlier, the above code MUST be placed in the Private Module of ThisWorkbook for the Add-in.
If you want the Super Code menu item added, say before the Format menu item, you could use some code like this.
Option Explicit
Dim cControl As CommandBarButton
Private Sub Workbook_AddinInstall()
Dim iContIndex As Integer
On Error Resume Next 'Just in case
'Delete any existing menu item that may have been left
Application.CommandBars("Worksheet Menu Bar").Controls("SuperCode").Delete
'Pass the Index of the "Format" menu item number to a Variable.
'Use the FindControl Method to find it's Index number. ID number _
is used in case of Customization
iContIndex = Application.CommandBars.FindControl(ID:=30006).Index
'Add the new menu item and Set a CommandBarButton Variable to it.
'Use the number passed to our Integer Variable to position it.
Set cControl = Application.CommandBars("Worksheet Menu Bar").Controls.Add(Before:=iContIndex)
'Work with the Variable
With cControl
.Caption = "Super Code"
.Style = msoButtonCaption
.OnAction = "MyGreatMacro"
'Macro stored in a Standard Module
End With
On Error GoTo 0
End Sub
There would be no need to change the Workbook_AddinUninstall() code in this case.
We have covered ID numbers while working with CommandBars etc in a P rior Newsletter Issue The link to the Microsoft site that has a BIG list of all the ID numbers for working with CommandBars can be Found Here
The above examples actually have the all the menu item code in the Workbook_AddinInstall and Workbook_AddinUnInstall Not a problem when the code is only adding one menu item. If however, you will be adding more then one and perhaps even Sub menus, you should place it in a Procedure (or 2) inside a standard Module. Then use some code as shown below
Private Sub Workbook_AddinInstall()
Run "AddMenus"
End Sub
Private Sub Workbook_AddinUninstall()
Run "DeleteMenu"
End Sub
Then in the standard module put some code perhaps like this
Sub AddMenus()
Dim cMenu1 As CommandBarControl
Dim cbMainMenuBar As CommandBar
Dim iHelpMenu As Integer
Dim cbcCutomMenu As CommandBarControl
'(1)Delete any existing one.We must use On Error Resume next _
in case it does not exist.
On Error Resume Next
Application.CommandBars("Worksheet Menu Bar").Controls("&NewMenu").Delete
'(2)Set a CommandBar variable to Worksheet menu bar
Set cbMainMenuBar = Application.CommandBars("Worksheet Menu Bar")
'(3)Return the Index number of the Help menu. We can then use _
this to place a custom menu before.
iHelpMenu = cbMainMenuBar.Controls("Help").Index
'(4)Add a Control to the "Worksheet Menu Bar" before Help
'Set a CommandBarControl variable to it
Set cbcCutomMenu = cbMainMenuBar.Controls.Add(Type:=msoControlPopup, Before:=iHelpMenu)
'(5)Give the control a caption
cbcCutomMenu.Caption = "&New Menu"
'(6)Working with our new Control, add a sub control and _
give it a Caption and tell it which macro to run (OnAction).
With cbcCutomMenu.Controls.Add(Type:=msoControlButton)
.Caption = "Menu 1"
.OnAction = "MyMacro1"
End With
'(6a)Add another sub control give it a Caption _
and tell it which macro to run (OnAction)
With cbcCutomMenu.Controls.Add(Type:=msoControlButton)
.Caption = "Menu 2"
.OnAction = "MyMacro2"
End With
'Repeat step "6a" for each menu item you want to add.
'Add another menu that will lead off to another menu
'Set a CommandBarControl variable to it
Set cbcCutomMenu = cbcCutomMenu.Controls.Add(Type:=msoControlPopup)
' Give the control a caption
cbcCutomMenu.Caption = "Next Menu"
'Add a control to the sub menu, just created above
With cbcCutomMenu.Controls.Add(Type:=msoControlButton)
.Caption = "&Charts"
.FaceId = 420
.OnAction = "MyMacro2"
End With
On Error GoTo 0
End Sub
Sub DeleteMenu()
On Error Resume Next
Application.CommandBars("Worksheet Menu Bar").Controls("&NewMenu").Delete
On Error GoTo 0
End Sub
You can find all details here.
http://www.ozgrid.com/VBA/excel-add-in-create.htm

vba - Msg if box if checked - but not if unchecked

I am trying to write code for a message to pop up if a checkbox is checked. My spreadsheet has a LOT of checkboxes, and I only want it to do this for the checkboxes in column H. I believe the best way may be to assign a macro to all checkboxes using vba using something like the following code (Except this is not working):
ActiveSheet.Shapes.Range(Array("h9:h89")).Select
Selection.OnAction = "Sheet4.Checkbox"
The second problem I have is that I only want the message to pop-up when it is checked, not when it is unchecked. The following works when the macro is assigned mannually, but for both checking and unchecking. The commented out sections are examples of some of the things I have tried. I believe they are ActiveX checkboxes.
Sub Checkbox()
' Dim rangeVar As Range
'
' rangeVar = ("h9:h89")
'
'With rangeVar
' If WorksheetFunction.Or(.Cells) = True Then
MsgBox ("Are you sure you want to check this box?")
Exit Sub
' End If
'End With
' Dim chk As Checkbox
'
' For Each chk In rangeVar
' If chk.Value = True Then
' MsgBox ("Are you sure you want to check this box?")
' Exit Sub
' End If
' Next chk
End Sub
Thank you!
Assigning the action:
Sub AssignClicks()
Dim cb
For Each cb In ActiveSheet.CheckBoxes
If Not Application.Intersect(cb.TopLeftCell, _
ActiveSheet.Range("H:H")) Is Nothing Then
cb.OnAction = "Sheet1.ClickedIt"
End If
Next cb
End Sub
In the sheet code module:
Sub ClickedIt()
Dim cb As CheckBox
Set cb = Me.CheckBoxes(Application.Caller)
If cb.Value = 1 Then
MsgBox "checkbox at " & cb.TopLeftCell.Address() & " is checked"
End If
End Sub
...or you can assign the action to all of your checkboxes and use code in ClickedIt to determine whether the current checkbox is in Col H.

(VBA) Putting ComboBox + macroevent on cell change

I'm trying to put a combobox inside active worksheet (but not activeX combobox), choose a list to fill and linked cell. It is an easy task, for example:
Sub make_combobox()
ActiveSheet.DropDowns.Add(69.75, 1.5, 79.5, 40.5).Select
Selection.Name = "combo"
ActiveSheet.Shapes("combo").Select
With Selection
.ListFillRange = "$A$1:$A$3"
.LinkedCell = "$D$1"
.DropDownLines = 8
.Display3DShading = False
End With
End Sub
I tried to put macro in worksheet containing this combobox, which will show msgbox whenever chosen linked cell is changed according to the chosen option in combobox. I wrote this in Worksheet section:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("D1")) Is Nothing Then
MsgBox "It works!"
End If
End Sub
Unfortunately, it doesn't work (Actually, it works when I change a value in D1 manually, but not work as a result of change in combobox).
Just assign a macro to the control using the OnAction property. It will run after every change made to the Combobox's value.

Excel - Returning the caption of the selected option button

Probably a silly question with a simple answer but I am a real novice when it comes to userforms.
I have "Frame 3" with 5 different option buttons (Dest1, Dest2, Dest3, Dest4, Dest5) After an option is selected, where is the caption value of the selected option stored? How can I access that with vba.
Thank you,
Josh
Here's just some example code you can use. Add your Option Buttons to groups, and then you can go from there. I used groups since you had multiple frames, and you can check based on group, and have multiple groups, and check which one's selected for each group.
Private Sub CommandButton1_Click()
Dim x As Control
' Loop through ALL the controls on the UserForm.
For Each x In Me.Controls
' Check to see if "Option" is in the Name of each control.
If InStr(x.Name, "Option") Then
' Check Group name.
If x.GroupName = "Grp1" Then
' Check the status of the OptionButton.
If x.Value = True Then
MsgBox x.Caption
Exit For
End If
End If
End If
Next
End Sub
You can also access the option buttons through the frame-ojbect that holds them (if you have other frames and controls you don't want to go through):
Option Explicit
Sub Test()
Dim oCtrl As Control
'***** Try only controls in Frame3
For Each oCtrl In Frame3.Controls
'***** Try only option buttons
If TypeName(oCtrl) = "OptionButton" Then
'***** Which one is checked?
If oCtrl.Value = True Then
'***** What's the caption?
Debug.Print "You have checked option " & oCtrl.Caption
Exit For
End If
End If
Next
End Sub
The Label Text associated with an Option Button is obtainable by using OptionButton1.Caption
If you are using a loop, just substitute the OptionButton1 with your variable for option buttons and it will pull through the one you need when conditions are met. eg:
For xitem = 1 To 5
xFrm = "OptionButton" & xitem
For Each fItem In Me.Controls
If fItem.Name Like xFrm Then
If fItem.Value Then
k = fitem.Caption
End If
End If
Next fItem
Next xitem
In my case, I wanted the caption of the toggle that was selected in an option group to be passed on to a subform filter. e.g. choosing toggle "black" filters subform to all cars where strColour = "black".
I ended up with this:
Private Sub OptionGroupName_Click()
Dim Caption As String
Caption = OptionGroupName.Controls.Item(OptionGroupName.Value - 1).Caption
Me.SubformName.Form.Filter = "[SubformField] = """ & Caption & """"
Me.SubformName.Form.FilterOn = True
End Sub
Not to dog pile on everyone else's options but I created a function that takes the radio group name and spits out the selected radios coresponding label caption. Was using it in Access not Excel.
Only works provided you name your controls similarly....
i.e. (lblRadioButton1 & optRadioButton1)
Function GetSelectedRadioButtonCaption(ByVal optionGroupName As OptionGroup) As String
Dim oCtrl As Control
Dim oCtrl2 As Control
Dim optionLabelName As String
Dim optionLabelObject As Label
Dim optionButtonObject As OptionButton
For Each oCtrl In optionGroupName.Controls
'***** Try only option buttons
If TypeOf oCtrl Is OptionButton Then
'***** Which one is checked?
Set optionButtonObject = oCtrl
If optionButtonObject.OptionValue = optionGroupName.Value Then
'***** What's the caption?
optionLabelName = Replace(oCtrl.Name, "opt", "lbl")
For Each oCtrl2 In optionGroupName.Controls
If oCtrl2.Name = optionLabelName Then
Set optionLabelObject = oCtrl2
GetSelectedRadioButtonCaption = optionLabelObject.caption
Exit For
End If
Next
End If
If GetSelectedRadioButtonCaption <> "" Then
Exit For
End If
End If
Next
Exit_GetSelectedRadioButtonCaption:
End Function

How to create a kind of variable Checkbox in vba excel

I have the next excel sheet with many checkboxs.
The problem is when I am coding I have to do some functions with Valor1 and Valor2 depending of if the checkbox is activate.
Well I have the code.
Option Explicit
Sub Casilladeverificación1_Haga_clic_en()
Range("c12").Activate
Do
If CheckBox1.Value Then
Call fucntion1
'Works for the first row, but for the second row int shoul be check CheckBox12 ,a next CheckBox23 ...
If CheckBox2.Value Then
Call fucntion1
If CheckBox2.Value Then
Call fucntion3
....
ActiveCell.Offset(1, 0).Activate
While Not IsEmpty(ActiveCell.Value2)
End Sub
But you can notice I dont want to made all the case with all the checkbox, there is a solve for this like checkbox[i]
I would put all of your functions into one big function and the functionality would separated by a Select Case block.
Private Sub functionRouter(checkAction as integer)
Select Case checkAction
Case 1
'Code for function one
Case 2
'Code for function two
''Etc.
End Select
End Sub
You're going to want to loop over all your check boxes. This is going to depend on what checkbox you are using.
Sub test()
Dim chkBox As CheckBox
Dim chkBox2 As OLEObject
'Regular
For Each chkBox In Sheets("Sheet1").CheckBoxes
Debug.Print chkBox.Caption
Next chkBox
'ActiveX
For Each chkBox2 In Sheets("Sheet1").OLEObjects
If TypeName(chkBox2.Object) = "CheckBox" Then
Debug.Print chkBox2.Object.Value
End If
Next chkBox2
You could do a few different things with all of your checkboxes. You could use the tagproperty (you would need to set all of them, but this allows for duplicates). Then call functionRouter(chkBox.tag) Or you could parse something from the name functionRouter Right(chkBox.name, 1)
You can iterate checkboxes on worksheet by using this loop:
For Each chk In ActiveSheet.CheckBoxes
MsgBox chk.Name
Next
It won't work if you use ActiveX controls though.