how to link a checkbox on Excel to a VBA code - excel

I have created a checkbox on my Excel Work sheet, using design mode I have leftclicked it and named it ChkV, and I wrote a VBA code but when I run it I get an message telling that the variable is not defined.
If ChkV.Value = True Then
' my code
End If
Did I not label the check box correctly, what am I doing wrong ? How should I fix the mistake?

Should it not be
If activesheet.Checkboxes("ChkV") = xlOn Then
'your code
End If
?

You have this error when you call your code outside Sheet module where your checkbox is located. To improve your code you need to add references to sheet where checkbox belongs to, like:
If Sheets("Sheet 1").ChkV.Value = True Then
' my code
End If

Hi i was breaking my head over and over again for this, but searching i found that you need to refer by the CodeName's sheet or using OleObjects
By Code Name is how you see in the VBA Project tree:
Hoja1.[CheckBoxName].Value
'' In English or what ever you may call your sheet is:
Sheet1.[CheckBoxName].Value
By OleObjects is:
Dim Wks as Worksheet
Set Wks = Worksheets("[SheetName]") '' in this case "Prueba"
Wks.OLEObjects("[CheckBoxName]").Object.Value
Note that my Excel is in Spanish thats why you see Hoja1, in English is Sheet1 and you can find something else here.

Related

Detect ComboBox Change Excel VBA

I have a sheet with a bunch of ComboBoxes(form control) and I want to detect when a user changes any one of them and write text in a cell. Using Worksheet_Change on the target cells doesn't work. I have tried a bunch of things that don't work. I'm not sure what needs to be in the private sub line or the if statement.
Private Sub DropDowns_DropButtonClick()
If ActiveSheet.DropDowns.Value > 1 Then
Cells(13, 5).Font.Bold = True
Cells(13, 5).Font.Color = vbRed
Cells(13, 5).Value = "!!! Selections have been changed. !!!"
End If
End Sub
I have tried
ComboBox_AfterUpdate()
ComboBox_Change()
DropDowns_AfterUpdate()
DropsDowns_Change()
and anything else I could find. I've also tried a few different things in the if statement with no luck.
I appreciate any help.
Chris
If I'm reading you correctly, you're comboboxes are in a userform. If I'm correct, simply open your userform in 'Visual Basic' and double click on the relavant combobox. This will open the code pane and create an empty Private Sub routine called 'Private Sub <Combobox Name> ()'.
Enter your code to place your data in the sheet (or whatever else you want) into the subroutine and Bob should be your uncle.
Apologies in advance if there's something I've missed.
RannochRob
Edit...
OK, my mistake, it's a form control.
My first comment is that it's easier to use an activex control if you can... however, with a form control, should (a) Use the cell link box in the 'Format Control' drop down ('Control' tab) to place the result in a cell... however, that result will not be the content of the box but an integer equal to the position of the selected entry on the list of entries in the combobox. You then need to (b) assign a macro to the combobox which will pick up the result and use it to get the required information from the range containing the list of entries. Like I say, much easier with an activex control...
RannochRob
Here's how you can do it by assigning a macro to the combobox (right click on the combobox>assign macro) as #BigBen mentioned in the comments section:
Option Explicit
Sub DropDown1_Change()
Dim sht As Worksheet
Dim dd As DropDown
Set sht = ThisWorkbook.Worksheets("Name of your Worksheet") 'Name of the worksheet in which the combobox is located
Set dd = sht.DropDowns("Drop Down 1") 'name of your combobox
sht.Range("G1").Value = "The selected value is: " & dd.List(dd.Value) 'dd.value returns the index of the selected value
End Sub
You can use the same code for each one of your comboboxes.
For demonstration purposes i have used the following set-up:
You can easily modify the code to best fit your needs.

How to reference a check box in VBA for Excel

I created a check box using the Developer Ribbon > Insert > ActiveX Controls > Check Box. I would like to code a sub which, when the box is checked, a range of values from the PCAPV10 worksheet is copied into a range on the BOM worksheet. I'm not sure if I am referencing my check box correctly in the code, and keep getting an object error. Any suggestions?
I've tried coding within the check box sub, and also referencing the check box from another sub. I can't seem to figure out either way to do this.
Private Sub CheckBox1_Click()
Dim PCAPV10 As Worksheet
Set PCAPV10 = Workbooks("CFC Calculation Program (Macro Enabled)").Sheets("Price Calculation APV10")
Dim BOM As Worksheet
Set BOM = Workbooks("CFC Calculation Program (Macro Enabled)").Sheets("BOM")
Dim chk1 As CheckBox
Set chk1 = Sheets("Price Calculation APV10").CheckBoxes("Check Box 1")
If Sheets("PCAPV10").OLEObjects("chk1").Object.Value = True Then
BOM.Range("A6:C120").Value = PCAPV10.Range("E11:I84").Value
End If
End Sub
I would like the code to recognize when the box is checked, and if true set the range within the BOM sheet equal to the range within the PCAPV10 sheet. If unchecked, do nothing. Instead, I am receiving the Run-time error '1004': Application-defined or Object-defined error.
No need to declare CheckBox1 As A Variable. You also put your variable PCAPV10 in Sheets(""). Try This:
If PCAPV10.OLEObjects("CheckBox1").Object.Value = True Then
BOM.Range("A6:C120").Value = PCAPV10.Range("E11:I84").Value
End If
If You Want To Define It, I'm Pretty Sure there isn't spaces:
Set chk1 = Sheets("Price Calculation APV10").CheckBoxes("CheckBox1")
You have already declared the check box and set the check box. Simply change the following:
If chk1.Value= 1 Then
This may not be the best practice, but I have always linked the check box to the cell it is in, so that cell toggles TRUE / FALSE.
Then I make the text match the fill color so it is not visible to the user.
Then in VBA I just use .range() or .cell() to match to that cell.
So I would use:
If Sheets("PCAPV10").range()
instead of what you have.

Textbox to a cell in hidden sheet

Im trying to make a macro for userform to input data in to hiden sheet. I have tryied application screening then visible the sheet and then input the data in a specific cell but ints not working like that.
Anyone know how it works?
You don't need to make a sheet visible to populate it.
For example, create a new workbook and make sure there is a sheet in there called Sheet2
Hide Sheet2
Put this into the debug window (ctrl-g) in the VB Editor
Sheets("Sheet2").range("A1").Formula = "Text in a hidden sheet"
press enter
Unhide Sheet2 and look at cell A1
Looks like thats not the only problem i have got. I will try to explain it. When a press a button a userform pop up and there is a text box in it. You write a name in the box, click a button and the name appears is a cell in one of the sheets that is hidden. That we already did.
Then i want to move to another sub which is located in one of the sheets. The other sub is for printing out a hidden sheet.
I have an Option Explicit there and
A sub called PrintFile.
Application.ScreenUpdating = False
With Sheets("Opis")
.Visible = True
.PrintOut
.Visible = False
End With
Application.ScreenUpdating = True
The problem is that it's giving me an error and i can't switch to the other sub.
Where im doing it wrong?

Excel Visual Basic Code Issue

I'm designing a PO that changes the cost per unit depending on the item selected in the Drop Down List.
I'm using...
Sub DropDown8_Change()
If (DropDown8.SelectedItem = "1") Then
Range("E21").Value = "54.90"
End If
End Sub
However I get the error,
Run-time error '424': Object required
If I remove the IF statement and have it simply change the contents of the Cell, It works.. So I'm assuming it is an issue with the Conditional Statement.
From my signifigant past with Visual Basic in Visual Studio, The name of the Control is included in the Method so I'm confused. I could be doing alot wrong here so bear with me :).
Thanks in advance
Working with Shapes on an Excel worksheet is kind of annoying. I usually stay away from them if I can.
Here's how you get the data you're looking for:
Sub DropDown8_Change()
Dim selectedItem As String
Dim ws As Excel.Worksheet
Set ws = Sheets(1)
Dim selectedIndex As Long
selectedIndex = ws.Shapes("Drop Down 8").ControlFormat.Value
selectedItem = ws.Shapes("Drop Down 8").ControlFormat.List(selectedIndex)
If (selectedItem = "1") Then
Range("E21").Value = "54.90"
End If
End Sub
The problem is that the method that's generated for you (in your case, DropDown8_Change()) doesn't really give you much to work with (like with Worksheet_Change(ByVal Target As Range)), and you have to deal with VBA Shapes (yuck).
You need to reference the Shape by it's actual name (unless you know the Shape's index, which isn't as easy to determine). The name can be found by right-clicking on the shape and then looking in the Range address textbox to the left of the formula bar. Then you have to go through this whole ControlFormat hoops to get what you're looking for.
Sorry for the rant. I hate VBA Shapes.

Excel Userform Combobox Properties Rowsource box issues?

I have a userform in Excel that works as a calculator.
In this userform I have two ComboBoxs (1 & 2)
In VBA editor, with ComboBox1 selected, In Properties, under Rowsourse I have: Sheet1!a4:a5
In Sheet1, A4 = Auckland and A5 = Christchurch
This is fine and when I run the userform there is a drop down arrow with the two options (Auckland or Christchurch).
However my problem is that when you open this workbook I have a VBA command to hide it from the users sight, leaving them only the userform to work with which is what is desired.
The issue is that if you have another workbook open then open this calculator workbook (which automatically hides itself). Then the combobox list is populated by Sheet1!a4:a5 on the other workbook that was already open, not the workbook that actually contains "Auckland" & "Christchurch" from which the userform is from.
I have tried making the Rowsource for the comboboxes more specific by putting the following in the rowsource box in properties: [book1.xlsm]sheet1!a4:a5 but this comes up with a "Invalid Property Value" error message.
I have also tried making a:
Private Sub Userform1_Initialize()
ComboBox1.Additem "Auckland"
ComboBox1.Additem "Christchurch"
End Sub
And also tried this:
Private Sub Userform1_Initialize()
ComboBox1.RowSource = Workbooks("book1.xlsm").Sheets("Sheet1").Range("a4:a5").Value
End Sub
However with both codes when it opens and runs now the comboboxes are empty and there is no list.
I think the easist solution would be to somehow put the full path (including workbook name) into the rowsource box under properties. But I must be missing something as its coming up with that error for me?
All help would be greatly appreciated.
Thanks
You are missing ' in your full path row source.
It should be like this:
Me.ComboBox1.RowSource = "'[book1.xlsm]Sheet1'!$A$4:$A$5"
I have similar question that can be found HERE.
Set the row source property of the combobox as: SheetName!$Col$Row:$Col$Row, e.g.: Location!$A$1:$A$3.
You may try adding this code on userform:
Private Sub UserForm_Initialize()
ComboBox1.list = Array("Auckland","Christchurch")
End Sub
Then set Combobox propert "MatchEntry" to "1".

Resources