VBA code to show Message Box popup if the formula in the target cell exceeds a certain value - vba

I am trying to write a simple macro to display a pop-up (vbOKOnly) if the value in a cell exceeds a certain value.
I basically have a worksheet with products and discounts. I have a formula in one cell, say A1, that shows the discount as a percent (50% or .5) effective discount of all the entries.
What I'm looking for is code to display a message box if the value of cell A1 exceeds say 50%, because the input of another cell pushed the discount over 50%.
Thanks!

You could add the following VBA code to your sheet:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A1") > 0.5 Then
MsgBox "Discount too high"
End If
End Sub
Every time a cell is changed on the sheet, it will check the value of cell A1.
Notes:
if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.
Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):
Pros: his method will work if A1's value is linked to cells located in other sheets.
Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.
Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

Essentially you want to add code to the Calculate event of the relevant Worksheet.
In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.
Alternatively, copy the code below into the editor of the sheet you want to use:
Private Sub Worksheet_Calculate()
If Sheets("MySheet").Range("A1").Value > 0.5 Then
MsgBox "Over 50%!", vbOKOnly
End If
End Sub
This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.

I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.

Related

VBA - Possibility of saying that SheetChange in specific Range is "something like True"?

First, I must admit that I am completely newbie here and in VBA mostly too. Thank you for this forum! :)
I have program that reacts on SheetChange to save the data. However, if there is formula added by macro, it doesn't cause the SheetChange. Copying and inserting as values isn't possible - there are 7k rows and the program acts on every SheetChange (colors and other stuff) - the time is not bearable.
Is there any possibility to have EnableEvents = False (to turn of getting SheetChange), then specify the Range of the changed cells (always rather the whole column - there are 2 columns only that interest me) and then let the program save data. The coloring of the cells and so on would remain (this coloring and so on has to stay in the program)
Is it even possible that it would work? If it could, how should I tell the macro that specific Range has SheetChange?
Apologies if the question is totally stupid.
Thank you very much for reading at least.
In the sheet change event, just specify that it should only save when Target is within the specified range. For the formulas, use the Calculate event and repeat essentially the same code.
So, if you only want it to save when the changed cell is in the first column and only within a certain row range (for example), add If Target.Column = 1 And Target.Row > 5 And Target.Row <= 10 Then to your change event.
For the Formula issue, add the following routine
Private Sub Worksheet_Calculate()
'your code here
End Sub

Is it possible to have a cell that has a formula and accepts entry at same time in excel?

Example:
A B
1 =vlookup(XX)
2
3
in cell A1 there is a Vlookup formula, Is it possible to enable user entry in this cell and override the formula then later restore the formula automatically when sheet is open again?
Even through VBA
Short, boring answer: nope.
A cell only ever has a keyed-in value, or a calculated formula. Can't have both.
Longer answer: maybe.
Shift everything 1 row down, and use row 1 to store your "original" formula - then hide that row (and pray the user isn't going to mess with it).
When the sheet is opened again sounds like you're confusing "workbook" and "worksheet" - you need to handle Workbook_Open if you want to run code when a workbook opens. Workbooks contain worksheets - it's the workbook that opens, not the sheets (sheets activate, but I doubt you would want to put that logic in there).
So, in the handler for Workbook_Open, write code that takes the formula in the hidden row and overwrites whatever is under it.
Another solution can be to hard-code the formula in the VBA code.
One possibility would be to store your Workbook as a template. Normally when a user opens the workbook by double-clicking, it will open whole new workbook based on the template, and they can modify it to their heart's content, save it, mail it to Grandma, etc.
The next person who comes along will double-click the template file and get the formula again, just as you designed it.
Short answer: Kind of, sort of
Long answer:
Save your workbook as a template. Every time someone will use it you'll see the orignal with formula, then if someone write over the formula, when using save your original will be kept intact.
What You need to do is:
press Alt + F11
select ThisWorkbook and paste this code:
Private Sub Workbook_Open()
Worksheets("Sheet1").Range("A11").Value = "asdf"
End Sub
Every time the workbook is opened, this script will run.
Instead of "Sheet1" you can write the name of the sheet you want to apply the script.
Inside the Range, You can define the cells you want to modify, You can use even multiple cells. Check this for more information about this.
After Value You can write what You want to be written inside the cell. You can write "=vlookup(XX)" and it will work.

How to highlight a cell when formula result from another sheet changes?

This is one that's been killing me and I've tried almost every solution on the Internet.
Here's background. I have an HR model that has each department broken out on separate tabs. I want to run an extract from our payroll system each payroll run and send highlight any updates individually. If someone's title or salary or status changes, I want to have that called out by highlighting the cell.
Each tab uses an INDEX/MATCH lookup to the extract tab to pull in the current information. What I want is if any value changes or is new(new hire, for example), highlight the cells.
I've played with Worksheet_Calculate and Worksheet_Change to no avail. Worksheet_Change doesn't fire because I'm not making the change directly on the sheet and Worksheet_Calculate doesn't have the Target object for to reference. I've tried the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim updatedCell As Range
Set updatedCell = Range(Target.Dependents.Address)
If Not Intersect(updatedCell, Range("A:A")) Is Nothing Then
updatedCell.Interior.ColorIndex = 3
End If
End Sub
The range I actually need evaluated is A7:R104 but I've been trying to get anything to work when linked to another sheet.
This works fine if formula of target cell is pointing to another cell on same sheet. The moment you point to one on another sheet it doesn't work. I've tried most of the solutions on here with no success. I've even tried putting the Worksheet_Change on the extract sheet and see if I can trigger it that way with no luck.
Is there a recommended solution to triggering a change to a cell for a formula linked to another sheet?
so I just saw this post, I don't know if you've found the solution or are still looking, but:
if you select a cell in sheet 3, you can then go to the home tab, go to "conditional formatting" -highlight cell rules - more rules (at the bottom) - and "use formulas to determine which cells to format" and then put your cursor in the formula box. now, select a cell in sheet 1 (click the sheet1 tab, and click a cell) and you'll notice it should populate the address for sheet1, and the cell u selected. now type <> after that cells address, then select sheet2 and a cell. then click format, and choose a fill color. then ok. if you go to conditional formatting and manage rules it will show there the rule / formula and which cells it applies to.
doing this i was able to select cell D10 in sheet 3, and make it an ugly green if cells in sheet1 and 2 didnt match (I picked which cells) you can also select a range of cells.
thusly, you can apply this rule to whatever dells you want, and if you record a macro of you setting this conditional formatting, you can manitpulate that macro to apply it to a bunch of different cells, and change the ranges. (using loops / variables)

How do I run VBA code on ListObject Change?

I know that I can write the following code in a sheets' VBA-object to run code on a worksheet change.
Private Sub Worksheet_Change(ByVal Target As Range)
End Sub
Is there anything similar that I can write to run code whenever I filter a certain ListObject?
Only in some cases. Say we include a new column in the table that we fill with the value 1. Elsewhere we insert an
=SUBTOTAL()
formula to sum that column. As the filter is operated the number of visible rows will vary. The SUBTOTAL() function will re-calculate.
At this point a Calculate Event macro would catch the re-calculation!
Try this...
I added a ListBox Form Control to my Excel sheet..
Next, I assign a macro to this object by Right Clicking and choosing "Assign Macro". (you may need to be in "Design Mode" to make this happen -- check the Developer Ribbon)
By default - the Macro Name is populated with a change event macro name. Click "New" to create the macro.
Your macro is added to a Module. Hope this helps!

VBA for clear value in specific range of cell and protected cell from being wash away formula

I have data from like A1:Z50 but I want to delete only A5:X50 using VBA
(I think it will be a lot faster than dragging the whole cell or using clickA5+shift+clickX50+delete).
How can I do this ?
And then, how to lock the cell to prevent it from getting fixed or cleared ?
You could define a macro containing the following code:
Sub DeleteA5X50()
Range("A5:X50").Select
Selection.ClearContents
end sub
Running the macro would select the range A5:x50 on the active worksheet and clear all the contents of the cells within that range.
To leave your formulas intact use the following instead:
Sub DeleteA5X50()
Range("A5:X50").Select
Selection.SpecialCells(xlCellTypeConstants, 23).Select
Selection.ClearContents
end sub
This will first select the overall range of cells you are interested in clearing the contents from and will then further limit the selection to only include cells which contain what excel considers to be 'Constants.'
You can do this manually in excel by selecting the range of cells, hitting 'f5' to bring up the 'Go To' dialog box and then clicking on the 'Special' button and choosing the 'Constants' option and clicking 'Ok'.
Try this
Sheets("your sheetname").range("A5:X50").Value = ""
You can also use
ActiveSheet.range
Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:
Ctrl-G
A1:X50 Enter
Delete
Unless you have to do this very often, entering and then triggering the VBAcode is more effort.
And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S to select Goto Special and here select Formulas or Values.