Expanding a number string formula - excel

I have an Excel formula that searches a string of 4 numbers, in a single cell comma separated, then divides them by 2 (rounding down).
e.g. cell A1 = 5,35,44,7
Formula in cell B1 = 2,17,22,3
I would like to extended the formula to accommodate a string of numbers anywhere from 1 through 15. The current formula that works perfect for a string of 1 to 4 numbers is below. I'm wanting to keep the formula to a single cell without using VBA. Thoughts on how to expand what I currently have?
=LEFT(IFERROR(ROUNDDOWN(MID(A2,1,IFERROR(SEARCH(",",A2,1)-1,LEN(A2)))/2,0),"")&","&IFERROR(ROUNDDOWN(MID(A2,SEARCH(",",A2,1)+1,IFERROR(SEARCH(",",A2,SEARCH(",",A2,1)+1)-SEARCH(",",A2,1)-1,LEN(A2)-SEARCH(",",A2,1)))/2,0),"")&","&IFERROR(ROUNDDOWN(MID(A2,SEARCH(",",A2,SEARCH(",",A2,1)+1)+1,IFERROR(SEARCH(",",A2,SEARCH(",",A2,SEARCH(",",A2,1)+1)+1)-SEARCH(",",A2,SEARCH(",",A2,1)+1)-1,LEN(A2)-SEARCH(",",A2,SEARCH(",",A2,1))))/2,0),"")&","&IFERROR(ROUNDDOWN(MID(A2,SEARCH(",",A2,SEARCH(",",A2,SEARCH(",",A2,1)+1)+1)+1,IFERROR(SEARCH(",",A2,SEARCH(",",A2,SEARCH(",",A2,SEARCH(",",A2,1)+1)+1)+1)-SEARCH(",",A2,SEARCH(",",A2,SEARCH(",",A2,1)+1)+1)-1,LEN(A2)-SEARCH(",",A2,SEARCH(",",A2,SEARCH(",",A2,1)+1)+1)))/2,0),""),LEN(A2))

This approach can handle nearly an unlimited number of items in a single cell, but it requires more than one formula.
Place the value in A1. In A2 enter:
=IFERROR(--ROUNDDOWN(TRIM(MID(SUBSTITUTE(A$1,",",REPT(" ",999)),ROWS($1:1)*999-998,999))/2,0),"")
and copy down. (these are the parsed individual values, divided by two, and then rounded down)
In B2 enter: =A2. In B3 enter:
=B2 & IF(A3="","","," & A3)
and copy down. (this performs the re-concatenation). Finally in C1 enter:
=INDEX(B:B,MATCH("",A:A,0))
It is MUCH easier to use VBA to solve this problem. This small UDF() does the same thing:
Public Function Brad(inpt As String) As String
Dim a
ary = Split(inpt, ",")
With Application.WorksheetFunction
For Each a In ary
Brad = Brad & "," & .RoundDown(CDbl(a) / 2, 0)
Next a
Brad = Mid(Brad, 2)
End With
End Function

Related

Looking for a way to split cells in excel based the last five numbers in a cell

I am looking for a way to fix a mixed data set representing addresses in Excel.
Here is an example dataset.
Kirchgasse 2389179 Beimerstetten
All this should result in three datasets.
A1 = Kirchgasse 2389179 Beimerstetten
A2 = Kirchgasse 23
A3 = 89179
A4 = Beimerstetten
Pattern is, that A3 is always the last 5 numbers in the dataset.
I am totally lost here, as Excel is usually not my weapon of choice.
You can use Excel Formulas as well, to split cells, Excel gives us ample opportunity to use the features, there are lot of ways for a query to resolve, you can follow any of the following approaches, to accomplish the desired output
To Extract The First Part From Cell A1, Formula Used In Cell A2
=LEFT($A1,FIND(" ",$A1)+2)
To Extract The Second Part From Cell A1, Formula Used In Cell A3
=LEFT(REPLACE($A1,1,LEN($A2),""),5)
To Extract The Last Part Of The String From Cell A1, Formula Used In Cell A4
=TRIM(RIGHT(SUBSTITUTE(A1," ",REPT(" ",100)),100))
However To Extract The 5 Numbers, you can use any one of the following as well that suits with your Excel Version
Formula shown in cell A11
=MAX(IFERROR(MID($A$1,ROW(INDIRECT("1:"&LEN($A$1))),5)*1,""))
Formula shown in cell A13
=LARGE(IFERROR(--MID($A1,SEQUENCE(LEN($A1)),COLUMN($A$1:$E$1)),0),1)
Formula shown in cell A15
=AGGREGATE(14,6,IFERROR(--MID($A1,ROW($1:$10000),COLUMN($A$1:$E$1)),0),1)
Formula shown in cell A17
=--RIGHT(FILTERXML("<p><w>"&SUBSTITUTE($A1," ","</w><w>")&"</w></p>","//w[.*0=0]"),5)
To get a detailed knowledge on FILTERXML Function you can refer the link below, prepared by JvdV Sir
FILTERXML FUNCTION DETAILED ANALYSIS BY JvdV Sir
Here is few more ways
Formula used in cell A2
=SUBSTITUTE(TRIM(FILTERXML("<p><w>"&SUBSTITUTE(SUBSTITUTE(LEFT($A1,FIND(" ",$A1)+2)&REPLACE($A1,1,FIND(" ",$A1)+2," ")," ","#",1)," ","</w><w>")&"</w></p>","//w")),"#"," ")
Just enter the formula in cell A2, and it will spill if you are using O365 or Excel 2021
And if you are not using the above Excel Version then you may try this and Fill Down The Formula
Formula Used In Cell B2 & Fill Down
=SUBSTITUTE(TRIM(FILTERXML("<p><w>"&SUBSTITUTE(SUBSTITUTE(LEFT($A$1,FIND(" ",$A$1)+2)&REPLACE($A$1,1,FIND(" ",$A$1)+2," ")," ","#",1)," ","</w><w>")&"</w></p>","//w["&ROW(A1)&"]")),"#"," ")
In A2, formula copied down :
=TRIM(SUBSTITUTE(MID(SUBSTITUTE(" "&REPLACE(REPLACE(A$1,AGGREGATE(14,6,FIND(ROW($1:$10)-1,A$1,COLUMN(A:Z)),1)-4,0," "),FIND(" ",A$1),1,"#")," ",REPT(" ",50)),ROW($A1)*50,50),"#"," "))
Put Kirchgasse 2389179 Beimerstetten in the A1 cell, and use the below VBA codes to set the D1 cell value as the last 5 numbers
Sub Test_Pattern()
Dim stringOne As String
Dim regexOne As Object
Set regexOne = New RegExp
regexOne.Pattern = "(\d{5})(?!.*\d)"
regexOne.Global = TRUE
regexOne.IgnoreCase = IgnoreCase
stringOne = Range("A1").Value
Set theMatches = regexOne.Execute(stringOne)
For Each Match In theMatches
Range("D1").Value = Match.Value
Next
End Sub
To learn how to use regex in VBA, see this ref

How can I substitute a cell reference for the formula the referred cell contains

How can I substitute a cell reference for the formula it contains, in other words, "expand" or "derivate" cell references?
An example, and I know I could calculate it using PV(): Suppose I want to calculate the present value of a given amount, reductor, number of periods and discount rate and in a spreadsheet I have:
A2: 1 (number of periods)
B2: 5000 (amount)
C2: 0,8 (reductor)
G1: 6% (discount rate)
If I want to calculate the final result on D2, I would have to enter:
=(B2*C2)*(1+$G$1)^(-A2)
(I intentionally used some unnecessary parentheses above)
But if I wanted, for debugging, or for building a more complex formula with more nested calculations write on cells:
D2: =E2*F2^G2
E2: =B2*C2
F2: =1+$G$1
G2: =-A2
So that I could check every part of the calculation is working ok and that the final formula is well "assembled" (or to easily correct what might be wrong or change it to calculate something else, like future value, for which I would remove the minus sign on G2).
And after doing those steps use some function/shortcut/feature on cell D2 that would replace
"=E2*F2^G2"
for
"=(B2*C2)*(1+$G$1)^(-A2)"
(i.e. do E2 → (B2*C2) F2 → (1+$G$1) and G2 → (-A2)) so that the desired formula is built on the right place and I can get rid of the temporary cells.
The closest to this behaviour I could find was formulatext() function, but it works just for a single reference and always include the "=" if I do, for instance
=CONCAT(FORMULATEXT(E2);"*";FORMULATEXT(F2);"^";FORMULATEXT(G2))
results in
=B2*C2*=1+$G$1^=-A2
which is not the desired result.
What I was expecting to find was something like when one select a part of a formula and presses F9 and it substitutes it for the value, but applied for functions or intermediate steps.
As it really does not seem to exist a built-in funcion on Excel, I came out with a script for doing this based on the answer on Parsing and extracting cell references from Excel formulas?
Works on Excel 365 (may work on other versions as well), replaces references on active cell only, does not work on cells that contain intervals (for instance, it will fail on a cell that contains =sum(A1:A5) ) and the contents of the precedent cells will end up enclosed in parentheses. It also does not replace "locked" cells (=$B$2 won't be replaced as well).
In summa, it is not perfect, maybe it's not ellegant too, but it seems to be as good as I needed and works on the proposed scope.
Sub ReplacePrecedents()
Dim r As Range, rr As Range
With ActiveCell.Range("A1")
' store the contents of the cell
parsedcontents = .Formula
Set r = .DirectPrecedents
' iterate throughout all precedents
For Each rr In r
' store each one between parentheses
appendstr = "("
' check whether first character is a "=" or a value
If StrComp(Left(rr.Range("A1").Formula, 1), "=") = 0 Then
appendstr = appendstr & Right(rr.Range("A1").Formula, Len(rr.Range("A1").Formula) - 1)
Else
appendstr = appendstr & rr.Range("A1").Formula
End If
appendstr = appendstr & ")"
' do the magic
parsedcontents = Replace(parsedcontents, rr.Address(0, 0), appendstr)
Next rr
' write the parsed string to the cell
.Formula = parsedcontents
End With
End Sub
Thank you for everyone that replied, I guess I still do not have privileges enough to upvote a comment, as soon as I do, I will.

excel function to combine cells into single line of text?

I'm new to stack overflow so I apologize if this is a horrendously stupid question. I am wondering if there is a function or way to code a function in excel that will combine a column of cells with plain text and convert them into one cell with the text on a single line? Specifically I want to convert a column of random numbers into a single line of text and insert SPACE+AND+SPACE between them.
Ex.
15133484
12345188
12345888
to
15133484 AND 12345188 AND 12345888
Currently I am copying and pasting all this information into google and then into Word and using find/replace and it is taking forever everytime. If it is possible to just get Excel to do this for me that would be amazing.
Thanks!
If you have Office 365 Excel use TEXTJOIN():
=TEXTJOIN(" AND ",TRUE,A:A)
otherwise one would have to use:
=A1 & " AND " & A2 & " AND " & A3
Or one can use a helper column, B1 put:
=A1
put this in B2 and copy down:
=IF(A2<>"",B1 & " AND " & A2,B1)
And grab the last cell in column B.
A little late, but still:
Reference here
Step 1:
=concatenate(transpose(rngBeg:rngEnd & " AND "))
Step 2:
highlight the transpose statement and then press F9, which substitutes the actual values for the formula.
Step 3:
Remove the curly braces, { }, from the formula. The cell will display the range of reference cells combined with whatever separator chosen after the ampersand sign.
Not a "live" formula, but still far easier than manually concatenating a range of values.
Press ALT+F11 to open Microsoft Visual Basic for Applications,
Insert-> Module
Paste this:
Function Combine(WorkRng As Range, Optional Sign As String = " AND ") As String
Dim Rng As Range
Dim OutStr As String
For Each Rng In WorkRng
If Rng.Text <> "," Then
OutStr = OutStr & Rng.Text & Sign
End If
Next
Combine = Left(OutStr, Len(OutStr) - 5)
End Function
In any cell type =Combine(Range)
i.e.
=Combine(A1:A500)
use concat function if you can add an additional column in the excel like this:
=CONCAT(D3:E5)
Attached sample image with input, additional column, output and formula
I assume you want to merge the data in the 3 cells into a single cell with a space between the 3 data set.
If that is the case then you can do it simply by using the Concatenate function in excel.
In the above example, you have data in Cells A1, A2 & A3.
Cell C1 has the merged data. As you can see, we have used CONCATENATE Function.
The space has been defined in Double quotes. So if you need a Hyphen (-), you can put that in Double Quotes with space “ - ” and it will display the result with Sanjay - Singh - Question
Hope this helps.

How do I input values in the Excel model without doing it manually?

I have the feeling that my previous question is being misunderstood. Therefore, I will do this as follows. What I would like is the following:
In this picture you see that the input is 4 in cell B1. This B1 cell is used as an input for a complicated model in a different sheet. The output of that model is linked to B2. I do not want to modify the complicated model on the other sheet (this part is required).
Now I would like to create a table like this:
So when the input is 4, the output from the model in the other sheet is 1. Now I can do this manually for 1, 2 and 3, by simply replacing the number written at B2 (which is 4) to 1 and check its output. Let’s observe what our complicated model gives us:
Apparently it gives us a 9, so I fill 9 in the F2. Now this is currently not a problem, since my table goes from 1 to 4. But how do I automate this? For example if I go from 1 to 100.
The problem is, you cannot touch or simplify the model on the other sheet.
How would one do this in VBA or do this in Excel itself?
I think you might have an issue in your explanation. Your example is A1 = 1, B1 = A1+5, despite saying it's A1 & A2. You are saying "Columns C & D" when I believe you mean "Rows 3 & 4).
If I understand your plight correctly, you are looking to drag down (auto-fill) the formula to the subsequent rows. You can do this with VBA, but you can do it without.
Provided you have data in the first column (A) as far as you would like the formula to travel, you can double-click from the lower right hand corner of the formula-reference cell and it will fill down. You could also drag the formula down by clicking and holding the lower right hand corner of the formula-reference cell.
You will know if you have the lower right hand corner if your cursor changes from from a "+" that is relatively large (with interior color) to a "+" that is relatively small (with no interior color... all black).
You will need to ensure that you have relative references when doing this, or ensure that your non-relative references are what you want. This is more than your question asked, but is important when doing this type of work.
See this:
Range("B1").Formula = A1 + 5
In this formula, A1 is relative to B1 by an off-set of -1 column. Every cell that the formula is pasted or dragged into will perform the formula with the cell that is -1 column relative.
You can add specifics to columns, rows, or cells, by use of "$". Say you have your example, and want to show the formula in Column C. There're 3 scenarios by using "$" which have different outcomes:
Fully relative, the dragged-formula will automatically designate the adjacent column.
Range("B1").Formula = A1 + 5
Range("C1").Formula = B1 + 5
Range("B2").Formula = A2 + 5
Range("C2").Formula = B2 + 5
If the "$" is in front of the column in the formula, the-dragged will "lock" the column, so when the formula is dragged, the column stays the same, but the row number will change.
Range("B1").Formula = $A1 + 5
Range("C1").Formula = $A1 + 5
Range("B2").Formula = $A2 + 5
Range("C2").Formula = $A2 + 5
If the "$" is in front of the row in the formula, the-dragged will "lock" the row, so when the formula is dragged, the row stays the same, but the column will change.
Range("B1").Formula = A$1 + 5
Range("C1").Formula = B$1 + 5
Range("B2").Formula = A$1 + 5
Range("C2").Formula = B$1 + 5
If the "$" is in front of the each the column and row in the formula, the-dragged will "lock" both. When the formula is dragged, the referenced-cell stays the same.
Range("B1").Formula = $A$1 + 5
Range("C1").Formula = $A$1 + 5
Range("B2").Formula = $A$1 + 5
Range("C2").Formula = $A$1 + 5
Hopefully that helps and is what you're looking for!
So you want to automate putting values through your model and recording the outputs.
A very simple approach begins with putting your list of inputs in column E as in your example picture. Note down the start and end row numbers - 2 and 5 in your example (as your input values are in the range E2:E5).
In the VBA editor created a new sub in a new module to hold your code (you can Google how to do this). The code is fairly simple.
Sub TurnInputsIntoOutputs()
' First we create some useful and important variables
Dim inputStartRow As Long ' The row your input values start on
Dim inputEndRow As Long ' The row your input values end on
Dim currentRow As Long ' A placeholder for when we cycle through the rows
Dim processingWorksheet As Worksheet ' How we're going to reference your worksheet
' Then we put values into those variables
inputStartRow = 2
inputEndRow = 5
Set processingWorksheet = ThisWorkbook.Sheets("*the name of your worksheet here*")
' Now we cycle through the input rows
For currentRow = inputStartRow to inputEndRow
' Put input value from the current row of column E into cell B1
processingWorksheet.Range("B1").Value = processingWorksheet.Range("E" & currentRow).Value
' Put the resulting output value into the current row of column F
processingWorksheet.Range("F" & currentRow).Value = processingWorksheet.Range("B2").Value
Next currentRow
End Sub
And then just run your macro (you can link it to a Form button or just run it from the VBE - easy enough for your to Google how to do).

Multiple Words in one Cell, How to separate without delimiting

Due to an erroneous online survey setup, the answers of a multiple choice, select all that apply question have all come together in one cell. For example:
All the selectable options are as follows:
A12 B1234 C3 D845 E00091 F
Cells with responses look as follows:
Cell A1: A12C3E00091
Cell A2: B1234F
Cell A3: C3D845F
And there are 100 cells like these with random responses.
I need to somehow automate the data extraction and then count each option.
I tried using Left, Right etc. Its not really helping.
I did use Find and then tried to extract data, but I'm unsure of a function that works from a specific start point within a cell.
If anyone could please help with this.
Thanks.
Copy your data to range A2:A101
into B1:G1, enter A,B,C,D,E,F
into B2, enter =LEN($A2)-LEN(SUBSTITUTE($A2,B$1,""))
copy B2 to B2:G101
result:
Kartike,
If I understand you right, you want to know which options are represtented in a cell with responses. I would say that you are right to use find. To test if option 1 is in cell A1 run:
=ISNUMBER(FIND("A12"; A1))
which returns TRUE if the string "A12" is included, and FALSE otheriwse. With the answer strings in a column down from A2 and the options strings in a row right from B1 you could get the full table of options by filling the rows and columns with
=ISNUMBER(FIND(B$1;$A2))
starting from cell B2.
Regards,
Mats
Copy this into a vba module and use Countwords(RangeString, SearchTerm) as a Cell function:
Public Function CountWords(r As String, Search As String) As Integer
Dim a As Variant, str As String, Count As Integer
For Each a In Range(r).Value
str = str & a
Next a
Count = (Len(str) - Len(Replace(str, Search, ""))) / Len(Search)
CountWords = Count
End Function
So =CountWords("A1:A10";"A12") Counts the A12s in the Range A1:A10.

Resources