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.
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
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
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
Related
I may or may not have an easy one here... For some reason I can't properly think of the solution.
Spreadsheet has numbers 1 to 14 in column A. 14 ends on row 15 as there is a header in cell A1. What I'm trying to do is double click one of these numbers and transfer that number to a specific cell on the same sheet (named "Sheet1"). I was able to put the code together to make it work for transferring a chosen number to a specific cell. Code below works well. However, I don't want to add a bunch of areas to double click for different cells. For example: The destination cell for the chosen data is E6, H6, and G6. I'd like to place the cursor starting in E6, double click a number in range A2 to A15, and have that number that I choose between A2 and A15 to appear in E6 since that is where the cursor was when I double clicked a cell in A2 to A15. Then I would move the cursor by click H6 and then going back to same selection between A2 to A15, placing whatever number I choose in that range in H6 since that is where the cursor currently exists.
Hopefully this makes sense and is even possible.
example screenshot
Working code that allows the double click to put data in a certain cell
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("A2:A15")) Is Nothing Then
Cancel = True
Target.Copy Destination:=Cells(6, "E")
End If
End Sub
I've added the solution I would try, with comments in the code. The reason for two sheet variables, is because the first click in the double-click registers as a SelectionChange event. So to get the correct cell location, you need it from two selections back, instead of just one.
Public selectedCell As String 'Sheet Variable
Public lastCell As String
' This updates the Sheet variable with the most recent selection
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
selectedCell = lastCell
lastCell = Target.Address
End Sub
' Added a check for having a previously selected cell
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("A2:A15")) Is Nothing Then
If selectedCell = vbNullString Then
Cancel = True
MsgBox "Please select a destination cell for the data."
selectedCell = vbNullString
lastCell = vbNullString 'Prevents overwriting same cell by accident
Else
Cancel = True
Target.Copy Destination:=Range(selectedCell)
selectedCell = vbNullString
lastCell = vbNullString 'Prevents overwriting same cell by accident
End If
End If
End Sub
Here is a tiny tool that you may be able to adapt to your needs. If you double-click on an empty cell, it becomes the FinalDestination. If you then double-click on another cell that is not empty, its contents will be copied to FinalDestination:
In the worksheet code area:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
Application.EnableEvents = False
If Target.Value = "" Then
Set FinalDestination = Target
Else
Target.Copy FinalDestination
End If
Application.EnableEvents = True
End Sub
In a standard module:
Public FinalDestination As Range
NOTE:
In this simple demo code there are no restrictions on source/destination.
I have created a Excel workbook for my work where I collect information. In this workbook I have a sheet where details in various currencies can be filled in. Based on the selection by the preparer the value in cell B5 will change to either USD or LC. In case the value in cell B5 will be USD, columns C and E should be hidden. The issue in here is that this code will not immediately unhide the columns. After clicking on a random cell, the columns are hidden. Please let me know if there is a solution for this issue whereby the columns are hidden without clicking on a random cell each time. Thank you.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("B5").Value = "USD" Then
Union(Columns("C"), Columns("E")).EntireColumn.Hidden = True
ElseIf Range("B5").Value = "LC" Then
Union(Columns("C"), Columns("E")).EntireColumn.Hidden = False
End If
End Sub
Thank you all for your comments. Let me further elaborate on my issue. In principle my VBA code works. The only thing is that after cell B5 is changed to USD, initially nothing happens. After I click on a random cell in this sheet, the VBA code works and hide the columns. The same is applicable in case the value in cell B5 is LC. Then again the VBA code does not work immediately. After clicking on a random cell in the sheet the columns are unhided.
A small update with respect to cell B5. So cell B5 contains a formula that is linked to listed cell in another sheet. After a value is selected from the list in another sheet, cell B5 will determine through the IF functions if the value in B5 will be LC or USD.
I am now afraid that after the preparer select in the listed cell a value, it will not click on a random cell in designated sheet resulting that he or she will see the wrong information.
Please let me know if you require further information. Thank you.
PS. I am not very strong in creating VBA codes.
You're using the wrong event.
SelectionChange fires when you select a different cell, etc.
Change fires immediately after a cell's contents change.
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("B5").Value = "USD" Then
Union(Columns("C"), Columns("E")).EntireColumn.Hidden = True
ElseIf Range("B5").Value = "LC" Then
Union(Columns("C"), Columns("E")).EntireColumn.Hidden = False
End If
End Sub
Alternate Solution:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target = Range("B5") Then Union(Columns("C"), Columns("E")).EntireColumn.Hidden = (Target.Value = "USD")
End Sub
(adapted from #Vityata's comment below)
More Information:
MSDN : Worksheet.SelectionChange Event (Excel)
MSDN : Worksheet.Change Event (Excel)
A few changes to your code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$5" Then
If Range("B5").Value = "USD" Then
Union(Columns("C"), Columns("E")).EntireColumn.Hidden = True
Else
Union(Columns("C"), Columns("E")).EntireColumn.Hidden = False
End If
Application.Calculate
End If
End Sub
1: the right event is Change (when a value changes in the sheet), not SelectionChange (when the selection changes).
2: Your code works on my side, so I guess it's not working on your side because you have some calculation off. I've added the line Application.Calculate which will refresh the spreadsheet even if your calculations are set to manual.
3: I've added an If Target.Address condition to check only when the cell that changed is the right one.
4: I've added just Else instead of ElseIf cell = "LC", because it's faster and because I think it's cleaner (if the user removes completely the value of the currency and before it was USD, nobody will unhide the columns C and E).
Keep it simple,
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim rng As Range
Set rng = Range("B5")
If rng.Value = "USD" Then Columns("C:E").EntireColumn.Hidden = True
If rng.Value = "LC" Then Columns("C:E").EntireColumn.Hidden = False
End Sub
I have the following piece of code on my workbook on my sheet, which is intended to test intersection using ws change and then go to the combo box and retrieve whatever value is entered in the box. However, what is happening is that after the value is entered in the combo box the first time the cell isn't updating with it's value. I have to click it again, and then it will populate. I know I have to likely use another event procedure, but I have no clue about combo box events. Can someone point me in the right direction?
Thx Mike.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim aRng As Range
Dim tRng As Range
Set aRng = Range("C19:C36")
Set tRng = Sheet2.Range("I2")
Application.EnableEvents = False 'to prevent re-iteration of event
On Error GoTo cleanup:
If Not Intersect(aRng, Target) Is Nothing Then
Call Sheet2.ComboBox1_Change
Target.Value = Sheet2.ComboBox1.Value
End If
cleanup: 'enable events once again
Application.EnableEvents = True
End Sub
and on Sheet 2 where the box is.
Public Sub ComboBox1_Change()
With ComboBox1
.Activate
.SelText = Empty
.DropDown
.MatchRequired = True
End With
End Sub
To get to the basics of your question, the Combobox has a LinkedCell property. If you enter the cell address on Sheet1 there, the selected item in the ComboBox will be displayed on Sheet1. (If a value is entered in that Cell on Sheet1, it will also be displayed in the ComboBox.)
ComboBox LinkedCell
You can force Sheet1 to be displayed after a selection is made in the ComboBox with this code (in the module of Sheet2):
Private Sub ComboBox1_Change()
Sheet1.Select
End Sub
Using Worksheet_Change will only have effect AFTER something has been entered into the cell (and RETURN has been hit).
I would like to create a button to hide the sheet. Ideally, it would hide the sheet where the button is located.
To be simple, sheet 1 has a form to fill out. The typical name, address, phone number, etc. Sheet 2 and 3 also have the same fields that is going to be referenced to the 'Data' tab as well. On a sheet named 'Data', I will add fields that will populate simply with the = option like (=Data!...)
However, I do not want the Data page in view once the information is added. We all know the simple right click and hide sheet. But sometimes that's too much for some people that will use this sheet and a pretty button would work better.
I was successful using:
Module 1
Sub SheetCommand()
If Worksheets("Sheet1").Range("C2").Value <> vbNullString Then
Worksheets("Sheet2").Visible = False
Else
Worksheets("Sheet2").Visible = True
End If
End Sub
Sheet1 Code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address <> "$C$2" Then Exit Sub
Run "SheetCommand"
End Sub
However, I am not very VB savvy and have hit a dead end. Could someone help show me how to apply this to a button? I don't want it to reference the $C$2 field as noted on the example, but just when someone presses the button, the sheet goes away. I'm not worried about getting it back as someone can be ready to get it the old fashioned way. This would help the data entry process for this manual form so much easier.
Edit: basically, I need help creating a vba code where I can hide the page. I'd like to create a button where once clicked, it hides that page. I showed an example of a code where I got it to work but it only works if that cell is populated. How do I make it work on button click?
I found this code that does what I need but I would like to tell it a specific Sheet Name instead of having to type it in B6 and B7.
Sub ShowHideWorksheets()
Dim Cell As Range
For Each Cell In Range("B6:B7")
ActiveWorkbook.Worksheets(Cell.Value).Visible = Not
ActiveWorkbook.Worksheets(Cell.Value).Visible
Next Cell
End Sub
It's actually not very clear to me what's your exact goal
for instance, assuming "Sheet 2" and "Sheet2" would point to the same sheet, in your question you seem to reference it as being both a "Form" sheet ("...sheet 1 has a form to fill out....Sheet 2 and 3 also have the same fields...") and "Data" sheet (Worksheets("Sheet2").Visible = False)
so here follow some possible solutions:
1) you want to hide "Data" sheet before closing the workbook it's contained in
then place the following code in "ThisWorkbook" code pane of the workbook containing "Data" sheet
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Worksheets("Data").Visible = False
End Sub
2) you want to hide "Data" sheet once some cells have been filled up in ANY sheet other than "Data"
then place the following code in "ThisWorkbook" code pane of the workbook containing "Data" sheet
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Sh.Name <> "Data" Then
With Sh
'here follows code to check if "the information is added"
'for instance:
If WorksheetFunction.CountA(.Range("A2:C2")) = .Range("A2:C2").Count Then ThisWorkbook.Worksheets("Data").Visible = False 'check if all cells in range "A2" to "C2" has been filled with some data
End With
End If
End Sub
3) you want to hide "Data" sheet once some cells have been filled up in ALL sheets other than "Data"
then place the following code in "ThisWorkbook" code pane of the workbook containing "Data" sheet
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim sht As Worksheet
Dim hideBool As Boolean: hideBool = True 'set initial value as true
If Sh.Name <> "Data" Then
For Each sht In ThisWorkbook.Worksheets
With Sh
'here follows code to check if "the information is added"
'for instance:
hideBool = hideBool And WorksheetFunction.CountA(.Range("A2:C2")) = .Range("A2:C2").Count ''check if all cells in range "A2" to "C2" of current sheet has been filled with some data
End With
If Not hideBool Then Exit For
Next sht
ThisWorkbook.Worksheets("Data").Visible = Not hideBool ' hide if ALL sheets met "information is added" condition
End If
End Sub
4) otherwise give more info about the desired behavior
How can i remove Formula from Excel Blank Cell, For Example i have these formula in one of the Blank Cells in Excel Dynamically.
=IF('filepath[filename.xls]Sheet1'!$A$1:A$65536="","",'filepath[filename.xls]Sheet1'!$A$1:A$65536).
Thanks
This will be some simple macro as:
Sub Macro1()
For Each c In Worksheets("your sheet name").Range("your range")
If c.Value = "" Then c.Select: Selection.ClearContents
Next c
End Sub
Where "your sheet name" can be for example "Sheet1"
and "your range" can be for example "a1:a10"
Private Sub Worksheet_Calculate()
Dim cell As Range
On Error GoTo finish
Application.EnableEvents = False
For Each cell In UsedRange
If cell.Text = "" Then cell.Clear
Next
finish:
Application.EnableEvents = True
End Sub
Unfortunately there is no way for Excel to provide a truly empty cell if it contains a formula, but I have a way to empty the cells:
Create an if statement that, if false, returns ERROR.TYPE(1).
From there, select the range of cells you want to delete the intended "blanks" from and use "Find and Select" >> "Go to Special".
Click on the "Formulas" radio button and leave "Errors" as the only box checked. Clicking OK will highlight all the cells that were assigned the value "#N/A".
Now just press the delete key.