Reputation: 20925
Is there a way (VB?) to add a formula dynamically to an excel cell?
I have a cell with conditions true and false, and they change based on a checkbox.
And I have another cell, which has a formula in it. This formula should be used if the checkbox is unchecked. If the checkbox is checked, then user should be able insert value manually (without any formula prompting there).So the formula should not be there.
I was thinking of a solution where I would add the formula to the cell if checkbox is unchecked, and then if the checkbox is checked, then I would clear the cell.
How could this be done? I'm not very familiar with excel coding and VBA.
Upvotes: 2
Views: 1423
Reputation: 14537
If you have a classical Excel CheckBox, you can add a Linked Cell which will be True or False.
In the following code, your Linked Cell is in A1
, the cell with the formula to use in B1
and the cell that need to be empty or filled by formula is in C1
.
You'll need to specify the Sheet_Name (can be differents) and place that code directly into the Sheet "module" in VBA (press Alt+F11
and double-click on the sheet (in the left panel) with the Linked Cell, then just paste and edit regarding your specifications)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim LinkedCell As Range, _
FormulaCell As Range, _
ChangingCell As Range
Set LinkedCell = Sheets("Sheet_Name").Range("A1")
Set FormulaCell = Sheets("Sheet_Name").Range("B1")
Set ChangingCell = Sheets("Sheet_Name").Range("C1")
If Application.Intersect(Target, LinkedCell) Is Nothing Then
'not in linked cell
Else
'in linked cell
If LinkedCell.Value2 <> True Then
'Unchecked
ChangingCell.FormulaLocal = ChangingCell.FormulaLocal
Else
'Checked
ChangingCell.FormulaLocal = vbNullString
End If
End If
Set LinkedCell = Nothing
Set FormulaCell = Nothing
Set ChangingCell = Nothing
End Sub
Upvotes: 0
Reputation: 433
well you could use:
if userform1.checkbox.checked = false then
range("A1").formula = "=myformula"
else
range("A1").value = ""
end if
you need to insert the code into the userform checkbox click or change event both should have same effect, just double click on the checkbox in userform and it will take you to the click event or replace the click with "change", hope that's what you meant to achieve, cheers PS. thanks for suggestions @99moorem
Upvotes: 1
Reputation: 138
Ok you need a trigger on TRUE/FALSE cell to execut the next VBA code, right click on sheet name and click "View Code" and enter this code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A5:A5")) Is Nothing Then 'define adress of your True/Flase cell
If Target.Cells.Value = False then
Range("B5").formula = "=enter your formula" 'define adress for cell with formula aswell
else
Range("B5").value = ""
end if
end if
end sub
Upvotes: 2