VBA multiple checkbox userform to single cell - excel

I am using a userform with multiple checkboxes in it. My goal is to have all checkboxes return their values (unique two letter acronyms) to a single cell. I am not sure how to accomplish this. I have no VBA experience prior to today.

You can record a macro to get your other relevant code for VBA but this should help:
Range("A" & LastRow).Value = CheckBox1.Value & CheckBox2.Value & CheckBox3.Value 'etc.
'Concatenate CheckBox values with "&" (the values will be True or False though)

Set linkcell of each checkbox to a different cell -.e.g. checkbox1 to cell A1, checkbox2 to cell A2, etc
For each link cell, use If formula in its adjacent cell to test the link cell's content and return a string or a blank,
e.g. if(A1=True,"AA","") in cell B1, if(A2=True,"BB","") in cell B2, etc
Finally, concatenate results of 'if' Formulas in another cell: e.g. B1&","&B2&","&B3, using comma as separaters

To do this, you can make a collection of all of the Checkboxes in the form. Heres my code:
Private mcolCHK As Collection 'This creates a modular level collection, which will keep track of all of the checkboxes
Private Sub cmdOK_Click()
Dim objA As Object, strResults As String, i As Integer
i = 1
For Each objA In mcolCHK
strResults = strResults & i & Left(objA.Value, 1)
i = 1 + i
Next
Unload frmTestForm 'rename this the name of your form
MsgBox strResults
'instead of using a message box, you can say "strResults = Sheets(sheet1).range("A1").value
'This part may be customized as needed
End Sub
Private Sub UserForm_Initialize()
Set mcolCHK = New Collection
mcolCHK.Add chkAtt1 'you will have to add one of these for each checkbox (simply replace "chkAtt1" with the name of your first checkbox
mcolCHK.Add chkAtt2 'and repeat for each checkbox
End Sub
Checkboxes always give a value of True or False. with this method, you will get the number of the checkbox (in order of how you added them to the collection in the UserForm_Initialize() sub) and the first letter of the result (T or F). When i ran this, I had two checkboxes, and checked each one when the form ran. This gave me a result of "1T2T". This can be changed as needed. All you really need is how this all works. just make sure to change all the names to match the names of the variables you used.

Related

Excel VBA: Control multiple pass/fail checkboxes with one macro

I have a test document that will have a lot of pass/fail checkboxes on it. The checkboxes are ActiveX and when clicked, I need them to print "Pass" or "Fail" to a cell that they are located in within the Sheet. I need them printed to the sheet because Excel's track changes doesn't record when the checkbox is clicked. These checkboxes are not part of a userform.
In my example below, Checkbox7 and Checkbox8 are located in cell C14. I have over 50 groups of the pass/fail checkboxes and I am trying to figure out a way that all of the checkboxes be handled by 1-2 Subs instead of having one per each checkbox.
Private Sub CheckBox7_Click()
If CheckBox7 = True Then
Range("C14").Value = "Pass"
Else
Range("C14").Value = ""
End If
End Sub
Private Sub CheckBox8_Click()
If CheckBox8 = True Then
Range("C14").Value = "Fail"
Else
Range("C14").Value = ""
End If
End Sub
I don't think I can use the same approach found in this solution since I'm not using a userform. Any suggestions/help would be much appreciated
You can do this without code.
In each Checkbox's properties, set the LinkedCell property to the cell that is covered by the checkbox. Just enter the address, like F2. This cell will now have the value of TRUE or FALSE depending upon the status of the checkbox.
In the cell where you want the comment, enter this formula (referring to the cell you linked to the checkbox), =IF(F2 = TRUE, "Failed", "")

Formula to hide rows based on the value of a cell

I have a worksheet that contains the names of all managers and their employees, ideally the way this sheet needs to work is that there is a drop down in the top left and when a manager selects their name, all rows that don't have their name against, are hidden, so only their team is shown.
I know auto filtering and having them choose their name would be the easiest way and is a good option to fall back on, but I'm hoping there is a way to do this with VBA or a formula to just hide rows when its not their team when they select their name in the drop down. As i'm trying to create something that's quite slick and looks nice
I did try to do something around having a helper cell to display true and false if the names matched, but came a bit stuck at this point. Tried using the code below, but it doesn't seem to actually be doing anything. Column with TRUE/FALSE is in Col A
Sub TEST()
Dim cell As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
For Each cell In Range("A4:A34")
If cell.Value = "FALSE" Then
cell.EntireRow.Hidden = True
Else
cell.EntireRow.Hidden = False
End If
Next
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Any ideas on how to do this without just using autofilter would be great
Given the following assumptions:
Drop down with Manager name is in cell A1
Column listing manager name for each row is in column A
Data set starts in row 5
Column A is contiguous with no blank spaces
Place the following code into the Worksheet module of the data sheet and change assumptions to fit your data set.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" and Target.Cells.Count = 1 Then
Application.ScreenUpdating = False
Range("A5:A1000").EntireRow.Hidden = False
Dim mgrList as Range
Set mgrList = Range(Range("A5"),Range("A5").End(xlDown))
Dim mgrCheck as Range
For each mgrCheck in mgrList
mgrCheck.EntireRow.Hidden = mgrCheck <> Target
Next
End If
End Sub
Use an if then else statement with a call that shows/hides the rows that you'd like to show.
If Range("A1").Value = "John Snow" Then
Call Show_John_Snow
Else
If Range("A1").Value = "Daenerys Targaryen" Then
Call Show_Daenerys
Else....
'subroutine
Show_John_Snow
Rows("17:20").EntireRow.Hidden = True 'hide others
Rows("21:53").EntireRow.Hidden = False 'show John Snow
Rows("54:75").EntireRow.Hidden = True 'hide others
I have this data, in which I have Headers at A3:D3, data starting from row 4 to 99.
I tried applying Autofilter, check if this one works for you.
Sub test()
Range("A3:D3").Select
Selection.AutoFilter
ActiveSheet.Range("A3:D99").AutoFilter Field:=2, Criteria1:="0"
ActiveSheet.Range("A3:D99").AutoFilter Field:=2, Criteria1:="1"
End Sub
Here, I selected option named "0" from drop-down filter from Field-2, that is Range A4, and as you told, other cells automatically gets hidden, and the cells corresponding to that criteria only gets visible.
Also I tried with other option "1".
This seems a very difficult or involved way to do this, I have to show students their results without them seeing other students results.
So, one sheet has all the data and on a "front" sheet I call the relevant data for the particular student using index() and match(). Each student has an ID number which is entered, then for confirmation the name is returned then the relevant grades.

Visual Basic Excel create Checkbox in Code

I've added a button to an Excel file which, when clicked, reads a text file and populates a column with lines from a text file. I need to add a checkbox to cells adjacent to certain lines, depending on what the line contains.
Can I create components like checkboxes in code, and if so, how?
Any responses are appreciated.
While the link #Siva provided is certainly valid I just prefer to have an answer on StackOverflow instead of an external link. Hence, here is the solution you might be looking for:
Option Explicit
Public Sub tmpSO()
Dim i As Long
Dim chk As CheckBox
With ThisWorkbook.Worksheets(1)
.CheckBoxes.Delete
For i = 1 To .Cells(.Rows.Count, "A").End(xlUp).Row
If .Cells(i, "A").Value2 = "need checkbox" Then
Set chk = .CheckBoxes.Add(Left:=.Cells(i, "B").Left, Top:=.Cells(i, "B").Top, Width:=.Cells(i, "B").Width, Height:=10)
chk.OnAction = "runThisSub"
chk.Name = "CheckBowInRow" & i
chk.Caption = "CheckBowInRow" & i
End If
Next i
End With
End Sub
Sub runThisSub()
MsgBox "You clicked the checkbox " & Application.Caller _
& Chr(10) & "in cell " & ThisWorkbook.Worksheets(1).CheckBoxes(Application.Caller).TopLeftCell.Address
End Sub
Copy both subs into a Module into your Excel file and change in the first sub
the sheet where the text is imported to (here it is Worksheet(1)),
the column where the condition can be found (here column A), and also
what the condition is (here the value in column A must be need checkbox).
The code will now look through all cells in column A in sheet Worksheet(1) and check if the value is need checkbox. If so, the code will automatically add a checkbox into column B adjacent to that cell.
If you click on any of the newly created checkboxes then the second sub fires up and will show you in a message box which checkbox in which row has been clicked.

Set cell vlookup value based on changing Combobox value

I have input a combobox in an Excel sheet. I want it to work so that the user who does not have access to the VBA can select a value from the dropdown and then the value in another cell will perform a vlookup on this value.
In the first instance I have inserted a box and am trying to set a cell value based on this.
Sub InsertComboBox()
#inserts dropdown box on the front page and sets the values as the list of DMA from the pipe_totals sheet
#this should be the most complete list so will not change dependant on asset
Dim arearange As Range
Set arearange = Sheets("pipe_totals").Range("a:a")
lastrowi = Application.WorksheetFunction.CountA(arearange)
Sheets("front page").Activate
With Range("f5:g5")
Set Combo = ActiveSheet.DropDowns.Add(.Left, .Top, .Width, .Height)
End With
Combo.List() = Sheets("pipe_totals").Range("A2:A" & lastrowi).Value
.Range("k9").Value = Combo.Value 'only works on current combobox value which is 0
End Sub
Is there a way I can set this so the vlookup is dynamic depending on the users selection?
In this example, just set the right combo name. It should be ok, provided that your combobox lists values from "Range("A2:A" & lastrowi)" as you mention above.
Sub "comboname"_Change()
Dim list_val As Long
list_val = Worksheets("front page").Shapes("comboname").ControlFormat.Value
Range("K9") = Worksheets("pipe_totals").Cells((list_val + 1), 1)
End Sub
Sub test()
Dim z As Shape
For Each z In Worksheets("front page").Shapes
Debug.Print z.Name
Next z
End Sub
As far as I understand, you want that everytime the combobox value changes, cell K9 will have the same value also. Is that right? If this the case, then right click on the combobox and select "Assign Macro". Then select "Create". Then inside the sub created, which should look like this:
Sub "comboname"_Change()
End Sub
You should also paste the final code line.
.Range("k9").Value = Combo.Value
Doing so, means you want that line of code executed every time the combobox value changes.

Excel copying value with VBA corresponding to a key after changing a cell

I am trying the folowing since a few days but due to my lack of VBA skills don't get it working.
Scenario:
User: Selects a value from dropdown list (cells allow only a list
defined in another sheet).
Code: Copy the value left to the appropriate list value. (This is a list of names.)
Code: Paste the value into a specific field in sheet one.
Example:
The user is picking the value "Team One" from a dropdownlist in A1 in sheet one. This list is defined on sheet two. Next to each item of the list on sheet two is a cell with a comma separated list of names.
After the user has picked a team from the dropdown list, the corresponding list of names is copied into the field B1 in sheet one.
This procedure should only be fired when A1 is changed.
Hope I could make myself clear. If I finally find the solution myself, I will post it here.
Thank you for reading this.
You can do this without VBA. In the field you want the list of names pasted into enter this formula:
=IF(ISBLANK(<address of dropdown on Sheet1>),"",INDEX(<address of list to left of values on Sheet2>,MATCH(<address of dropdown on Sheet1>,<address of dropdown values on Sheet2>,0)))
This will be blank when nothing is selected from the dropdown and will display the appropriate list of names when a value is selected.
For example, if the dropdown is in B1 on Sheet1, the dropdown values are in B1:B9 on Sheet2, and the corresponding list of names are in A1:A9 on Sheet2, you would use this formula:
=IF(ISBLANK(Sheet1!B1),"",INDEX(Sheet2!A1:A9,MATCH(Sheet1!B1,Sheet2!B1:B9,0)))
EDIT (per comment):
To use this in VBA, you'll need to do something similar to what #chris neilsen suggested. In the Worksheet module, you'll need to create a sub for a change event:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B1")) Is Nothing Then
Range("A1").Formula = "=INDEX(Sheet2!A1:A9,MATCH(Sheet1!B1,Sheet2!B1:B9,0))"
If IsError(Range("A1").Value) Then
Range("A1") = ""
Else
Range("A1").Value = Range("A1")
End If
End If
End Sub
To remove any confusion, A1 is the cell that will display the output.
To do this as VBA, you would do something like the following. Per your original question, there is a list on Sheet2 that corresponds to the selection from the dropdown box and populates on Sheet1.
In the VBA editor:
In Sheet1, add the following methods
Private Sub ComboBox1_Change()
If ComboBox1.Text <> "Select" Then
Dim selVal As String
selVal = ComboBox1.Text
Range("B1").Value = GetList(selVal)
End If
End Sub
Public Function GetList(ByVal Value As String) As Variant
Dim result As Variant
result = Application.VLookup(Value, Worksheets("Sheet2").Range("A1:B100"), 2, False)
GetList = result
End Function
In the workbook object code, enter the following method:
Private Sub Workbook_Open()
With ThisWorkbook.Worksheets("Sheet1").ComboBox1
.AddItem "Team One"
.AddItem "Team Two"
.AddItem "Team Three"
.AddItem "Team Four"
.AddItem "Team Five"
.Text = IIf(.Text = "", "Select", .Text)
End With
Worksheets("Sheet1").Activate
End Sub
I should note that you could do this without any vba by simply using a a list control found in the Data Validation option in Excel. When you make a selection change in that, you would then use a standard VLookup in cell B1 to grab the corresponding value(s).
To implement this in VBA, use a Change event to monitor the data entry cell.
Assuming you have named your validation data range as ListData, put his in the module for Sheet1
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" Then
[B1] = Application.WorksheetFunction.VLookup(Target.Value, [ListData].Resize(, 2), 2, 0)
End If
End Sub
I would advocate an approach similar to the one that Excellll described, but with VLOOKUP rather than MATCH. To do this, you'd need to have your lists of names to the right of each team's name. For example:
| A | B
1 |Team 1 |Albert, Beth
2 |Team 2 |Carlo, Delia
3 |Team 3 |Egbert, Frederika
Now, if the team's name is at cell B7, you could use this formula to get the associated list of names:
=VLOOKUP(B7, Sheet2!$A$1:$B$3, 2, FALSE)
EDIT
See Doug Glancy's comment below explaining why Excellll's solution is better than using VLOOKUP.

Resources