I'm trying to change the background color of a form control checkbox via VBA code. I've tried every variation of code I can find on the internet and am still getting failures.
The line I have currently is below, and is the only one I've found so far that doesn't give me compiler errors. When I run it though I get a "Run-time error '438': Object doesn't support this property or method" error on executing this line. This is true whether I set it = to xlBlack, RGB(255,255,255) or "11398133" (not black I know, but I was just trying to see if any color would work).
Anyone know what's going on and how I can actually do this?
Sheets("Controls").Shapes.Range(Array("Check Box 8")).BackColor = "11398133"
Answer
I found the answer. For some reason none of the responses worked, but Johnny's answer did help me get closer to it by loading the right object in memory and I could then use the Locals window to track down the property I wanted.
In the end it was identifying the object as Johnny suggested and then just cb.Interior.Color = xlBlack I was looking for. No .Fill and no .DrawingObject. Not sure what makes this different than others that would make that work that way, but there you go.
So, for any others who come looking, the code that ended up working for me was the simple addition of the below, and you can find out what the Excel name of the object is (Check Box 8 in my case) by selecting it while recording macros.
For Each cb In Sheets("Controls").CheckBoxes
If cb.Name = "Check Box 8" Then
cb.Interior.Color = xlNone
Exit Sub
End If
Next
This should do it for you. Follow these steps:
Make some form check boxes on a sheet
Copy the below code into a module (alt F11, insert, module)
run SetMacro
Save and test
code:
Sub SetMacro()
Dim cb, ws
For Each ws In ThisWorkbook.Sheets
For Each cb In ws.CheckBoxes
If cb.OnAction = "" Then cb.OnAction = "CheckedUnchecked"
Next cb
Next ws
End Sub
Sub CheckedUnchecked()
With ActiveSheet.Shapes(Application.Caller).DrawingObject
If .Value = 1 Then
.Interior.ColorIndex = 4
Else
.Interior.ColorIndex = 2
End If
End With
If you're only looking to do it on the active sheet, use this block instead:
Sub SetMacro()
Dim cb
For Each cb In ActiveSheet.CheckBoxes
If cb.OnAction = "" Then cb.OnAction = "CheckedUnchecked"
Next cb
End Sub
Sub CheckedUnchecked()
With ActiveSheet.Shapes(Application.Caller).DrawingObject
If .Value = 1 Then
.Interior.ColorIndex = 4
Else
.Interior.ColorIndex = 2
End If
End With
End Sub
Another possibility is that you want to set the ForeColor not the BackColor.
Very simply:
Sub changegColor()
Dim wb As Workbook
Dim ws As Worksheet
Dim cb As Object
Dim rng As Range
Set wb = ActiveWorkbook
Set ws = wb.ActiveSheet
Set cb = ws.Shapes.Range(1)
With cb.Fill
.Solid
.ForeColor.RGB = RGB(0, 255, 0)
End With
End Sub
Related
Apologies any incorrect terms, this is the first time I am trying to code a macro. I currently have the following code running:
Private Sub Worksheet_Deactivate()
'Alpha Show / Hide
If Sheets("Project_selection").Range("D4") = Range("C2") Then
Sheet3.EnableCalculation = True
ElseIf Sheets("Project_selection").Range("D4") = "All" Then
Sheet3.EnableCalculation = True
Else
Sheet3.EnableCalculation = False
End If
End Sub
which has been cobbled together from other codes and google. It works, but only when I move out of the sheet, which I think is being driven by the first line.
I would actually like it to activate when the Cell D4 in the 'Project_selection' sheet (a separate sheet to the one the code is on) gets changed - does anyone know how I would do that? I have seen references to worksheet_change, but I do not understand how one defines the target/range to get the appropriate reference.
Hope that makes sense and thanks in advance!
If you were to place the following code under the sheet (Project_selection), it would fire that event every time a change has happened in Cell D4:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet: Set ws = Sheets("Project_selection")
If Target.Address = "$D$4" Then
If ws.Range("D4") = ws.Range("C2") Then
Sheet3.EnableCalculation = True
ElseIf ws.Range("D4") = "All" Then
Sheet3.EnableCalculation = True
Else
Sheet3.EnableCalculation = False
End If
End If
End Sub
I have a table with the following values:
Now, I would like to call the Userform in column H based on the value in column G, but I can't work out how to call the Userform based on the cell value. The error occurs in line
form.Name = wsControls.Cells(loop2, 8).Value
Here is my code:
Sub Check_Scenarios()
Dim wsAbsatz As Worksheet
Dim wsControls As Worksheet
Dim wsData As Worksheet
Dim loop1 As Long
Dim loop2 As Long
Dim lngKW As Long
Dim form As UserForm
Set wsAbsatz = ThisWorkbook.Worksheets("Production")
Set wsData = ThisWorkbook.Worksheets("Data")
Set wsControls = ThisWorkbook.Worksheets("Controls")
lngKW = wsControls.Cells(1, 2).Value + 2
If lngKW = 3 Then
Exit Sub
End If
For loop1 = wsControls.Cells(10, 2).Value To wsControls.Cells(19, 2).Value Step 10
If wsData.Cells(loop1 + 3, lngKW).Value <> "" Then
MsgBox (wsData.Cells(loop1 + 3, lngKW).Value)
For loop2 = 2 To 16
If wsData.Cells(loop1 + 3, lngKW).Value = wsControls.Cells(loop2, 7).Value Then
form.Name = wsControls.Cells(loop2, 8).Value 'error occurs here
form.Show
End If
Next loop2
End If
Next loop1
End Sub
Project:
Many thanks for your help!
You are trying to assign a Name to a blueprint. These are two errors.
You have to initialize your blueprint as something. Like this:
Dim form As New UserForm
Then, most probably your UserForm does not have a property called Name. It is called Caption. Thus it is like this:
Sub TestMe()
Dim uf As New UserForm1 'judging from your screenshot
uf.Caption = "Testing"
uf.Show
End Sub
Disclaimer:
There is a better way to work with UserForms, not abusing the blueprint, although almost every VBA book shows this UserForm.Show method (in fact every single one I have read so far).
If you have the time and the OOP knowledge implement the ideas from here - or from my interpretation of the ideas. There was also a documentation article about it in StackOverflow, but it was deleted with the whole documentation idea.
You don't "call" a userform. You instantiate it, and then you Show it.
UserForm is the "base class" from which all userforms are derived. See there is inheritance in VBA, only not with custom classes.
So you have a UserForm2 class, a UserForm3 class, a UserForm4 class, and so on.
These classes need to be instantiated before they can be used.
Dim theForm As UserForm
Set theForm = New UserForm2
theForm.Show
Set theForm = New UserForm3
theForm.Show
'...
So what you need is a way to parameterize this Set theForm = New ????? part.
And you can't. Because whatever you're going to do, the contents of a cell is going to be a string, and there's no way you can get an instance of a UserForm3 out of a String that says "UserForm3".
Make a factory function that does the translation:
Public Function CreateForm(ByVal formName As String) As UserForm
Select Case formName
Case "UserForm1"
Set CreateForm = New UserForm1
Case "UserForm2"
Set CreateForm = New UserForm2
Case "UserForm3"
Set CreateForm = New UserForm3
'...
End Select
End Function
And then call that function to get your form object:
Set form = CreateForm(wsControls.Cells(loop2, 8).Value)
If Not form Is Nothing Then form.Show
I'm going crazy trying to find a way for code to run when I click on ANY of the checkboxes on my sheet. I've seen multiple articles talking about making a class module, but I can't seem to get it to work.
I have code that will populate column B to match column C. Whatever I manually type into C10 will populate into B10, even if C10 is a formula: =D9. So, I can type TRUE into D10 and the formula in C10 will result in: TRUE and then the code populates B10 to say: TRUE. Awesome... the trick is to have a checkbox linked to D10. When I click the checkbox, D10 says TRUE and the formula in C10 says TRUE, but that is as far as it goes. The VBA code does not recognize the checkbox click. If I then click on the sheet (selection change), then the code will run, so I know I need a different event.
It is easy enough to change the event to "Checkbox1_Click()", but I want it to work for ANY checkbox I click. I'm not having ANY luck after days of searching and trying different things.
here is the code I'm running so far
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim i As Long
For i = 3 To 11
Range("B" & i).Value = Range("c" & i)
Next i
End Sub
Any help would be appreciated.
this works
' this goes into sheet code
Private Sub Worksheet_Activate()
activateCheckBoxes
End Sub
.
' put all this code in class a module and name the class module "ChkClass"
Option Explicit
Public WithEvents ChkBoxGroup As MSForms.CheckBox
Private Sub ChkBoxGroup_Change()
Debug.Print "ChkBoxGroup_Change"
End Sub
Private Sub ChkBoxGroup_Click()
Debug.Print "ChkBoxGroup_Click"; vbTab;
Debug.Print ChkBoxGroup.Caption; vbTab; ChkBoxGroup.Value
ChkBoxGroup.TopLeftCell.Offset(0, 2) = ChkBoxGroup.Value
End Sub
.
' this code goes into a module
Option Explicit
Dim CheckBoxes() As New ChkClass
Const numChkBoxes = 20
'
Sub doCheckBoxes()
makeCheckBoxes
activateCheckBoxes
End Sub
Sub makeCheckBoxes() ' creates a column of checkBoxes
Dim sht As Worksheet
Set sht = ActiveSheet
Dim i As Integer
For i = 1 To sht.Shapes.Count
' Debug.Print sht.Shapes(1).Properties
sht.Shapes(1).Delete
DoEvents
Next i
Dim xSize As Integer: xSize = 2 ' horizontal size (number of cells)
Dim ySize As Integer: ySize = 1 ' vertical size
Dim t As Range
Set t = sht.Range("b2").Resize(ySize, xSize)
For i = 1 To numChkBoxes
sht.Shapes.AddOLEObject ClassType:="Forms.CheckBox.1", Left:=t.Left, Top:=t.Top, Width:=t.Width - 2, Height:=t.Height
DoEvents
Set t = t.Offset(ySize)
Next i
End Sub
Sub activateCheckBoxes() ' assigns all checkBoxes on worksheet to ChkClass.ChkBoxGroup
Dim sht As Worksheet
Set sht = ActiveSheet
ReDim CheckBoxes(1 To 1)
Dim i As Integer
For i = 1 To sht.Shapes.Count
ReDim Preserve CheckBoxes(1 To i)
Set CheckBoxes(i).ChkBoxGroup = sht.Shapes(i).OLEFormat.Object.Object
Next i
End Sub
All you need is to let EVERY checkbox's _Click() event know that you want to run the Worksheet_SelectionChange event. To do so you need to add the following line into every _Click() sub:
Call Worksheet_SelectionChange(Range("a1"))
Please note that it is irrelevant what range is passed to the SelectionChange sub since you do not use the Target in your code.
I am trying to replace all of the conditional formatting of a spreadsheet (over 30 formatting rules). I have created a class module (called ConditionalFormatting) that has a series of subs for all the formatting rules, with one sub for each range that needs conditional formatting.
The only way I have thought to do this (open to suggestions) is by having the worksheet_change event call a sub in the ConditionalFormatting class called FormattingSubs which will call the correct sub to perform the formatting.
Here is the code for FormattingSubs:
Public Sub FormattingSubs(target As Range)
'have logic here to call the right sub based on what target.address
'is from the worksheet.change event
Select Case target.Name.Name
Case "head_pouch_lot_number"
Call HeadPouchLotNumber(target)
Case "head_consumed_pouch_lot"
Call HeadConsumedPouchLot(target)
Case "section_one_heading"
Call SectionOneHeading
End Select
End Sub
And here is the code for one of the formatting subs, HeadConsumedPouchLot: (note that the color variables are public constants defined in a separate module)
Public Sub HeadConsumedPouchLot(target As Range)
Dim head_consumed_pouch_lot As Range
Dim ws As Worksheet
Set head_consumed_pouch_lot = ActiveSheet.Range("head_consumed_pouch_lot")
Set ws = target.Worksheet
If target.address <> head_consumed_pouch_lot.address Then
Set target = head_consumed_pouch_lot
End If
With ws.Range(target.address)
If Range("section_one_heading").Value <> "" Then
.Interior.ColorIndex = red
.Font.ColorIndex = yellow
Else
.Interior.ColorIndex = lightgreen
.Font.ColorIndex = black
End If
End With
The problem is that when it goes to actually set the color, it gives me the 1004 error: "Application-defined or object-defined error."
What is wrong with my code?
The problem I figured out was that I needed to unprotect my sheet before I could make any changes to it! Thank you all for helping me look for answers.
This question already has answers here:
Microsoft Excel ActiveX Controls Disabled?
(11 answers)
Closed 8 years ago.
I have been using this excel program for several months without issues. suddenly a couple days ago it started to throw this error. On sheet named "Input" I will double click a cell in column "A" which will create a drop down box that will fill with data from the "Data" sheet. I start typing and then I select the data to add to the cell. Now when I click the cell and get an error message "Compile Error - Method or data member not found". Here is my block of code and the error is showing near the bottom highlighting "Me.TempCombo.Activate".
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim str As String
Dim cboTemp As OLEObject
Dim ws As Worksheet
Set ws = ActiveSheet
If Target.Column = 1 And Target.Row > 12 And Target.Row <> HRRow And Target.Row <> HRRow - 1 Then
lRow = Sheets("Data").Range("A65536").End(xlUp).Row
Set cboTemp = ws.OLEObjects("TempCombo")
On Error Resume Next
With cboTemp
'clear and hide the combo box
.ListFillRange = ""
.LinkedCell = ""
.Visible = False
End With
On Error GoTo errHandler
'If Target.Validation.Type = 3 Then
'if the cell contains a data validation list
Cancel = True
Application.EnableEvents = False
'get the data validation formula
'str = Target.Validation.Formula1
'str = Right(str, Len(str) - 1)
str = "=Data!A2:A" & lRow
With cboTemp
'show the combobox with the list
.Visible = True
.Left = Target.Left
.Top = Target.Top
.Width = Target.Width + 5
.Height = Target.Height + 5
.ListFillRange = str
.LinkedCell = Target.Address
End With
'cboTemp.Activate
Me.TempCombo.Activate
'open the drop down list automatically
Me.TempCombo.DropDown
End If
errHandler:
Application.EnableEvents = True
Exit Sub
End Sub
I tried several things and for the life of me I cannot figure out what changed.
Any help will be appreciated. Thank you.
I ran into the same error and was able to solve it as Rory suggested. I searched my machine for *.exd files and found a few. The issue was solved for me after removing C:\Users\<username>\AppData\Local\Temp\Excel8.0\MSForms.exd...the others seemed to be unrelated to the ActiveX controls in Excel.
Looks like the code came from an example like this: http://www.contextures.com/xlDataVal10.html
except your code has commented out the line which activates the cboTemp combobox. Your code is attempting to access the TempCombo attribute of the worksheet (which I don't think exists). Uncomment 'cboTemp.Activate on the line above the highlighted error line.
I had the same problem, my code broke this morning. Fortunately, I recalled that I ran Windows Update this weekend. I performend a system restore (earliest available restore point was 8th of december), and now the problem is gone.
I never did understand the panicy server guys who were always making backups and spending a whole lot of time testing before/after system updates, in all my years I never experienced any problems. Now I sure figured out what they were talking about. Lesson learnt. I'll try running win update again in a few months, hopefully MS has solved the problem by then.
Best of luck