Dynamic Excel Subtraction - excel

Say I've got cells A1-A10 populated with numbers. My initial formula in cell B1 is =A1-A6. However, I'd like to strike-out cell A3 (keeping the contents visible underneath the strike-out if possible), and I'd like the formula in B1 to recognise that change, and then automatically adjust itself to =A1-A7 (the idea being that I'd like A1 subtracted by the number in the cell 5 "non-struck out" cells below it). And then if I strike out cell A5 I'd like the formula to adjust itself to =A1-A8 and so on. Does anyone know how to do this?

(EDIT#1: misread the input, sorry)
A bit straightforward, but will do the job: type =A1-INDIRECT("A"&SMALL(IF(A:A<>"",ROW(A:A),""),6)) and press CTRL+SHIFT+ENTER instead of usual ENTER - this will define an ARRAY formula and will result in {} brackets around it (but do NOT type them manually!).
To speed up calculation you may replace A:A to any limited range.
Sample file (resulting formula is yellow-marked): https://www.dropbox.com/s/sy7zkg71xtfgib9/Subtract5th.xlsx
(EDIT#2: misread the "strike-out", sorry)
Font styles (as well as similar cell properties) may NOT be read by default Excel functions, that's why you need to add UDF called StrikeOut:
Press ALT-F11 - thiss will open VBA editor.
Insert new module: Insert > Module.
Paste the code to added module:
Function StrikeOut(R As Range) As Long
Dim c As Range
StrikeOut = 0
For Each c In R.Cells
If c.Font.Strikethrough = True Then StrikeOut = StrikeOut + 1
Next
End Function
Add the formula to B1: =A1-INDIRECT("A"&(6+StrikeOut(A2:A10)))
Set strikethrough font to any cells in A1:A10.
Unfortunately, cell format change does NOT trigger any change event, so you need either press F9 or change any cell value on the sheet to recalculate and therefore update result in B1.
Sample file is shared: https://www.dropbox.com/s/n9o7tn3ks3x8nza/StrikeOut.xlsm
P.S. at least for me that was extremely useful)))

Related

How to dynamically access column properties in a With Range statement for conditional formatting

I am trying to write a script to take an easy look into my data. The data is structured as follows:
Row 1: Parameter Name
Row 2: Lower Limit
Row 3: Upper Limit
Row 4: Unit
Row 5 and below: data (can go up to a couple thousands lines and couple hundred columns).
The thing I want to achieve is a script which formats each cell from row 5 down, to color green if it is in between the limits, and to color red if it is not. Each cell should look to it's own column row 2 and 3 for the limits.
I have tried going cell per cell, or column by column. Both worked fine on smaller datasets, but showed problems (excel freezing and eventually closing) on bigger datasets.
I am now trying to format a complete range (because excel has no problems when I do a big range in one piece by hand whatsoever) at once, but I can't access the individual column properties.
The code I am using:
With formatRange
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, Formula1:="=" & Cells(2, formatRange.Column).Address, Formula2:="=" & Cells(3, formatRange.Column).Address
.FormatConditions(1).Interior.Color = RGB(0, 249, 49)
End With
Now say my range is from A5:B10.
formatRange will be A5:B10.
I would expect every cell from A5:A10 to compare their values against A2 and A3. This is indeed the case
But the cells of B5:B10 also compare their values against A2 and A3.
So my question is, is there a scalable way I can make range B5:B10 look at B2 and B3 instead?
Edit
The answer of #Ryan B. is an easy and correct way of doing it by hand.
The problem in vba turned out to be the following:
Formula1:="=" & Cells(2, formatRange.Column).Address would ultimately result in Formula1:="=$A$2"
As suggested by the accepted answer, this needed to change to Formula1:="=A$2" to work.
The solution I found was to create a function which cut of the first character, and create the correct formula this way.
This can be done by tricking Excel's absolute and relative referencing within conditional formulas. No VBA is going to be required. Here is a quick mock of how I understand your data:
Select the first cell of your 'Row 5' range -- where you're going to apply the conditional formulas.
Open the conditional formatting dialog from the Styles button group in the Home Ribbon (this is B5 in my mock-up),
Create a 'New Rule'
Choose 'Use a formula to determine which cells to format' rule type
Begin typing the following rule. You will have to be quite careful and avoid all use of the arrow keys. If you need to get to a different point in the formula, use your mouse to move the insertion point. Make the proper adjustment in your formula if that initial column isn't column 'B' in your worksheet
=AND( B5 >= B$2, B5 < B$3)
Pay special notice to the Dollar Signs. There are NO absolute references used for the target cell, B5. There are absolute references (that's the dollar sign) in front of the row numbers for Lower and Upper, but not on the columns.
Set you're desired look for the "in-bounds" formatting and select OK.
Repeat the steps for your "out-of-bounds" formatting. Use the formula
=OR( B5 < B$2, B5 >= B$3)
Finally, to apply the formulas to your entire range:
Select the cell with the prepared formulas (B5 in this example) and hit [ctrl] + [c] to put excel into cut/copy mode
Select the entire target range
Right click and take 'Paste Special' from the context menu
Paste as formats
And your formatting should propagate through the worksheet.
Hope it helps. Always experiment on a copy of your workbook :)

Excel Formula - Check if cell has formula

What formula do you use to check if another cell has formula? For example, I have 2 columns, A has cells which contains either a formula or a value.
(Column A usually contains Formulas but other users try to change their values by directly typing and replacing the formula that was previously there)
In Column B I want to add a formula that will say "HasFormula" if the cell on Column A has formula and say "PlainValue" if it contains a value.
I'm thinking maybe using =ISNUMBER() but that may not be accurate.
I am using Excel 2010.
Excel actually has a builtin ISFORMULA() function.
Say A1 has a formula and you want to check that. In say B1, you can use:
=If(ISFORMULA(A1),"HasFormula","PlainValue")
Edit: Per your comment, you don't have ISFORMULA(). An alternative is to create a quick UDF, and use the custom function in the worksheet.
In a workbook module, put this code:
Function isFormula(ByVal target As Range) As Boolean
isFormula = target.hasFormula
End Function
Then you can call it like this: =isFormula(A1) and it will return TRUE if A1 has a formula.
If you can't use VBA, then you can use this formula:
=IF(ISERROR(FORMULATEXT(A1)),"PlainText","HasFormula")
The MrExcel website (link below) has this method which uses old code from Excel 4 (which is still present for backward compatibility)...
Define a NAME such as "CellToLeftHasFormula" and in the "refers to" box put
=GET.CELL(48,OFFSET(INDIRECT("RC",FALSE),0,-1))
Then in column B use the formula =CellToLeftHasFormula which will return TRUE if it has.
Be aware that this will mean your Excel will now contain a macro and so will need to be saved as such (xlsm). I use this in Excel 2010.
For full explanation (and other .CELL options, besides 48) see MrExcel link: https://www.mrexcel.com/forum/excel-questions/20611-info-only-get-cell-arguments.html
You can use the Range.HasFormula property.
https://learn.microsoft.com/en-us/office/vba/api/excel.range.hasformula
EDIT:
Text and code from the above link:
"True if all cells in the range contain formulas; False if none of the cells in the range contains a formula; null otherwise. Read-only Variant. ..."
Worksheets("Sheet1").Activate
Set rr = Application.InputBox( _
prompt:="Select a range on this worksheet", _
Type:=8)
If rr.HasFormula = True Then
MsgBox "Every cell in the selection contains a formula"
End If
You can restrict the user by protecting the column A.
You can directly check if a cell contains a formula by using a shortcut Ctrl + `.
You can use vba and write a user defined function :
1. Press alt + F11
2. Insert module in workbook
3. Paste this code
Function IsFormula(cell_ref As Range)
IsFormula = cell_ref.HasFormula
End Function
4. Now, use Isformula in the cell wherever you want.

Excel VBA Add formula based on row

So I have that table above, I use Excel VBA to add new prices then add the formula to Decision column.
As you can see, cell B2 formula should be =IF($A2>50000,"Ignore","Buy") and cell B3 formula should be =IF($A3>50000,"Ignore","Buy") so the formula in B2 refers to the value in A2, this is the same for B3 to A3 and so on. I use the VBA below to add the same formula to blank cells. Yes, there will be blank decision cells and they need formula. I must NOT use autofill from top to bottom. I tried using below (LastRow is the usedrange.row):
Sheet1.Range("B2:B" & LastRow).SpecialCells(xlCellTypeBlanks). _
Formula = "=IF($A2>50000,""Ignore"",""Buy"")"
The problem with that VBA is even in cell B5 the formula is =IF($A2>50000,""Ignore"",""Buy"") when it should be =IF($A5>50000,""Ignore"",""Buy"") (should be $A5 instead of $A2). What am I doing wrong?
With SpecialCells(xlCellTypeBlanks) you will probably get a non continuous range. With this the auto fill process will not work with A1 formulas. But with R1C1formulas it will.
Use:
.Range("B2:B" & lastrow).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=IF(RC1>50000,""Ignore"",""Buy"")"
RC1 means the Row you are currently in but always fix Column 1.
For R1C1 references see https://support.office.com/en-us/article/Overview-of-formulas-7abfda78-eff3-4cc6-b4a7-6350d512d2dc?CorrelationId=2bedf5ef-a3b7-4a82-9b12-6ee86b494ae9&ui=en-US&rs=en-US&ad=US#bmusing_references_in_formulas. Scroll down to The R1C1 reference style.
You can paste the formula in all cells, considering you have the formula in cell "B2":
Range("B2").Copy
Range("B2:B" & LastRow).PasteSpecial xlPasteFormulas
edit for more detail: You can use the R1C1 reference style, more importantly, R[1]C[1] notation. There is a caveat for different languages though, see the very end of the post. Examples:
R2C4 'row 2, column 4 so it's the cell D2 in A1-notation
R[2]C[4] 'the cell 2 to the right and 4 down from the current cell (where this reference is located)
R[2]C4 'the cell 2 to the right from the current cell in column 4 (D)
R[-2]C[-4] 'you can also give negative arguments, this is the cell 2 to the left and 4 up
R[2]C 'the same as R[2]C[0]
RC[4] 'the same as R[0]C[4]
R2C 'the same as R2C[0]
RC4 'the same as R[0]C4
R2 'row 2
C4 'column 4 (the same as D:D)
As you can see from the last three examples, the notations can't be mixed.
Now for your case:
If you want to have the following in cell Bx (replace x by any number)
"=IF($Ax>50000,""Ignore"",""Buy"")"
This would be the R1C1 formula
"=IF(RC1>50000,""Ignore"",""Buy"")"
or if it is more important that it is the column to the left:
"=IF(RC[-1]>50000,""Ignore"",""Buy"")"
The latter would be the like dropping the $ from the original formula.
Your second formula was
"=IFERROR(VLOOKUP(RC3,Database!$A:$F,3,FALSE),""Missing"")"
and Axel's answer
"=IFERROR(VLOOKUP(RC3,Database!C1:C6,3,FALSE),""Missing"")"
should be clear now.
If you don't want or can't use the formulaR1C1 property but still use the R1C1 style reference for a single cell, you can use the INDIRECT worksheet function. INDIRECT("R1C1",FALSE) is a reference to R1C1. The FALSE tells it to use R1C1 instead of A1 notation. It might behave slightly different than a simple reference if there is something other than numbers in the referenced cell.
I personally like the R1C1 notation better than the A1 notation mostly because it is easier to reference cells relative to the current position but also because it is easier to read for high column numbers and it's closer to the Cells(rowIndex,columnIndex) syntax.
One last thing: In other language versions of excel, R1C1 might be named differently. That doesn't affect the formula when you enter it via VBA (I think) but if you want to enter it from the worksheet, you need to keep that in mind. In German it's Z1S1 for example. This can also cause problems when opening the file with a different language version. If you used INDIRECT("R1C1",FALSE) in a formula, the INDIRECT and FALSE will be translated but the string will not so it will not work :( (The last part is from memory)

Applying a formula to a group of cells

I'm trying to do a formula where it is CELL / 127.05 - 1 and apply this to columns H-Y and rows 2-455. I'm not really familiar with excel and am going about this calculation cell by cell. Also, I'm running into a "circular" problem where certain cells rely on another, if anyone could explain this.
Thanks ahead of time!
A formula in a cell generally cannot refer to itself. If you want to apply an operation to an existing range of data, you can, but it is quite rare and surely not in the spirit of a spreadsheet app.
Regarding your question, you could
- enter a value (127.05) anywhere in an empty cell,
- then copy that cell
- then select the range you want to modify
- then select Paste Special / Divide (or any other operation)
As I said above, it sounds like you want to apply that formula to same cell that contains the value you want to act on. That will not work. results cells (i.e. containing your conclusions) will contain the formula and a reference to the cell it will act on. (Although I am using a smaller area for illustration, the principles will apply to your specific application)
Note - I used the randbetween(min,max) function to populate all the data cells. this is why each image contains different data. You of course will use cells containing static data.
For a simple example:
Say you put the value 127.05 in cell A1, and have a range of data cells, like this:
In cell F1, enter = b1/$a$1 - 1 like this:
Note, the $ signs tell Excel to use a static location cell reference. After hitting enter, the value -0.85045 will appear. Now, click and hold your mouse starting in that cell, and drag your mouse down to row 14 release the mouse button and hit keys <ctrl><d>. Your sheet should look like this:
Hold down the shift key while the column is still selected, and hit the right arrow key 3 times, Your sheet should look like this:
release the shift key and while the cells are all highlighted, hit keys <ctrl><r>. The results are here:
One way is to highlight the column (or specific range) you want to apply the formula to, press F2 to access the formula bar, type the formula, and press CTRL+D to paste DOWN if the range is vertical and CTRL+R to paste ACROSS if the range is horizontal. Say that your data looks like this:
A B
--- ---
5 A1/127-1
4
7
8
Then in order to copy the formula down, highlight A2 to A4 and press CTRL+D, or highlight B1, and click on the bottom right of the box that comes up surrounding the cell.
If you wanted to simply replace the values in A with their formula values you would still have to use Column B as a 'helper' column, rather than entering the value right into the cell. This is in fact exactly what is giving you the circular reference error.
Regarding the circular error, you may be trying to apply the formula to the cell you are already in. For example, if you are trying to apply the formula A1 / 127 - 1 in the cell A1 Excel won't know what to do because you have specified that the value of A1 is both the value in the specified cell and another value ( A1 / 127 - 1), which can't be true.
Now, the only way I know of to do what you're requesting is with VBA, because I realized just now that I asked a very similar question a while ago which was helpfully answered by Gary. The code was as follows:
Sub Formulate()
Dim N As Long, i As Long, dq As String
N = Cells(Rows.Count, "A").End(xlUp).Row
dq = Chr(34)
For i = 1 To N
v = Cells(i, 1).Value
Cells(i, 1).Formula = "=Text(" & v & "," & dq & "mm/dd/yyyy" & dq & ")"
Next i
End Sub

Excel formula to show linked cell ID

In an excel cell, I've placed a simple formula
=C4
The cell typically displays the value of cell C4, but instead I want to see the linked cell ID instead, which in this case is "C4".
Is there a formula to show me this? like:
=SHOWCELL(C4)
The reason I need this instead of simply typing the value of "C4" into the cell, is so Excel will maintain the link to the correct cell even if rows are inserted/deleted, AND show me which cell is linked.
You should be able to use the Cell function.
In Excel, the Cell function can be used to retrieve information about a cell. This can include contents, formatting, size, etc.
=Cell("address", C4)
This displays $C$4.
When inserting a row before C4, it is changed to $C$5.
In case you do not want the $ signs, one way would be the Substitute function:
=Substitute( Cell("address", C4), "$", "" )
You can create your own User Defined Function to achieve this. I call it "CellReference".
Usage:
=CellReference(B6)
displays "B6"
To use it, launch VBA, insert a module, and then copy the below into the module:
Function CellReference(cell As range) As String
CellReference = cell.Address(0, 0, xlA1)
End Function

Resources