Display Value Does Not Match Data Value After Split Function - excel

I'm writing a macro that parses a string in a cell from my excel sheet and should return the three coordinates in that string. I can get the script to parse the string fine and create a "coordinateHolder" array to hold the three coordinates. My issue is that when I update cells to show the coordinates excel shows does not show the entire coordinate.
For example, if the coordinates string is originally "1234.1324123, 12345.23521, 2384.1234253", my code will update my x, y, and z coordinate cells as "1234.132", "12345", "2384.1234"
Image of what I mean:
(This one shows scientific notation in the cell and a shortened double in the formula builder bar)
My Code:
Dim i, j As Integer
Dim coordinates As String
Dim coordHolder As Variant
i = 2
j = 1
Range("I2:K2").Value = Range("E2:G2").Value
Do While Cells(i, j) <> ""
coordinates = Cells(i, j)
coordinates = Replace(coordinates, ",", "")
coordHolder = Split(coordinates, " ")
For a = 0 To UBound(coordHolder)
Cells(i, 7 + a) = coordHolder(a)
Next a
i = i + 1
Loop

Excel has a limit of 15 digits for numbers. Any number with more digits will lose precision in the lower magnitudes to enable the number display. Your data has values that go beyond the limit and will be truncated.
513402938412.123 shows just 15 digits. The remaining decimal places have been removed. The significance of 4 or more decimals pales in comparison with the magnitude of the value, therefore Excel considers the digits after the third deicmal as dispensable.
If you want to retain all digits in the value, you need to convert it to text and make sure it remains text and is not converted to a number again. To do that, you can precede any number with the apostrophe sign.
If a cell contains the value 5134029388412.12341234 it will be truncated. A cell containing the value '5134029388412.12341234 will be treated as text and remain intact.

Related

VBA(excel) numbers as string comparation

How to compare numbers as string?
I want to compare f.ex. 2 and 10. When i sort them in Excel in ascending order 2 is before 10, but when i compare in VBA those two 10 seems to be lower number than 2. I'm using strcomp function. I need to compare them as strings beacuse it's a part of bigger program that's searching for the identical strings in excel columns. Strings can be normal strings, numbers and number-ish strings as "12-131xxx".
Mnich, with StrComp, either vbBinaryCompare or vbTextCompare will give you the returns you're currently getting. When Excel sorts numbers/integers, it sorts as you would expect, but when sorting numbers as strings, it uses a textual comparison; so all numbers starting with 1, even 111, will be ranked lower than 2. As Comintern mentions, you have to add leading zeros to get away with this.
Or, perhaps, you replied one number comparison before you ranked the strings, you could try a Function to extract the numbers, then let that weigh your decision:
'pass in array from main stuff
Function StackOverflow(arr())
Dim arr_NewStr() As String
Dim x As Integer
Dim i As Integer
ReDim arr_NewStr(1 To UBound(arr))
x = 1
For i = 1 To UBound(arr)
Do
If IsNumeric(Mid(arr(i), x, 1)) Then
arr_NewStr = arr_NewStr & Mid(arr(i), x, 1)
End If
x = x + 1
Loop Until x = Len(arr(i))
Next
'clean up
x = vbEmpty: i = vbEmpty
'pass somewhere, or make "arr" public
End Function

Multiply two 100-Digit Numbers inside Excel Using Matrix

I want to multiply two 100-Digit Numbers In Excel using matrix. The issue in Excel is that after 15-digit, it shows only 0. So, the output also need to be in a Matrix.
1st Number: "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"
2nd Number: "2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222"
Output: "22222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222217777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777778"
This may be what OP was after. I thought I would try a naive multiplication method to see how long it would take to run. The answer is less than a second for two 100-digit numbers. You have to select the output range (i.e. A3:GR3 for a 200-digit result) and enter the formula containing the input ranges as an array formula using CtrlShiftEnter e.g.
=Multiply(A1:CV1,A2:CV2)
for two 100-digit numbers.
The method is basically just a simulation of school maths long multiplication, except that the intermediate rows are not stored but immediately added to the answer thus saving a lot of space.
The utility of it is obviously not that it is a replacement for the Karatsuba method, but it is a simple verifiable method which could be used for one-off calculations.
Currently limited to multiplication of rows containing more than one cell (so if you wanted to multiply by a single digit number, would have to enter it as e.g. 09).
Start of numbers
Middle of numbers
End of numbers
Function Multiply(rng1 As Variant, rng2 As Variant)
Dim arr() As Integer
Dim arrLength, r1Length, r2Length, carry, product, digit As Integer
Dim tot, totDigit, totCarry As Integer
Dim v1, v2 As Variant
v1 = rng1
v2 = rng2
r1Length = UBound(v1, 2)
r2Length = UBound(v2, 2)
arrLength = r1Length + r2Length
' Declare 1D array with enough space
ReDim arr(1 To arrLength)
' Loop over digits in first number starting from right
For i = r1Length To 1 Step -1
carry = 0
totCarry = 0
' Loop over digits in second number starting from right
For j = r2Length To 1 Step -1
' Calculate next digit in intermediate values (i.e. one row of long multiplication)
product = v1(1, i) * v2(1, j) + carry
digit = product Mod 10
carry = Int(product / 10)
' Calculate next digit in final values (i.e. totals line of long multiplication)
tot = arr(i + j) + digit + totCarry
arr(i + j) = tot Mod 10
totCarry = Int(tot / 10)
Next j
' Process final carry
arr(i) = carry + totCarry
Next i
' Return as an array
Multiply = arr
End Function
OK it might work like this:-
(1) You need to concatenate your numbers into a string because that's what you need as the input to your function. Native Excel won't do concatenation on arrays so you need a UDF like this one. So B2 contains
=concat(D1:G1)
(2) The output from the function is a string so you need to split it back into separate cells. You could use another UDF or a formula like this one copied across:-
=IF(COLUMNS($C3:C3)>LEN($B$3),"",VALUE(MID($B3,COLUMNS($C3:C3),1)))
So for the simple example it would look like this:-
But I might have got the wrong end of the stick completely.
Place your arrays into A1:A100 and B1:B100, then use three formulas:
1) In C2:C200 enter this as an array formula:
=MMULT(IFERROR(INDEX(A1:A100*TRANSPOSE(B1:B100),(ROW(INDIRECT("1:"&ROWS(A1:A100)*2-1))>0)+TRANSPOSE(ROW(INDIRECT("1:"&ROWS(A1:A100))))-1,MOD(ROW(INDIRECT("1:"&ROWS(A1:A100)*2-1))-TRANSPOSE(ROW(INDIRECT("1:"&ROWS(A1:A100)))),ROWS(A1:A100)*2-1)+1),0),SIGN(A1:A100+1))
2) In D1 enter =C1+INT(D2/10) and fill down to D200.
3) In E1 enter =MOD(D1,10) and fill down to D200.
E1:E200 will contain the answer.

Split Cell by Numbers Within Cell

I have some fields that need to be split up into different cells. They are in the following format:
Numbers on Mission 21 0 21
Numbers on Mission 5 1 6
The desired output would be 4 separate cells. The first would contain the words in the string "Numbers on Mission" and the subsequent cells would have each number, which is determined by a space. So for the first example the numbers to extract would be 21, 0, 21. Each would be in its own cell next to the string value. And for the second: 5, 1, 6.
I tried using a split function but wasn't sure how to target the numbers specifically, and to identify the numbers based on the spaces separating them.
Pertinent to your first case (Numbers on Mission), the simple solution could be as shown below:
Sub SplitCells()
Const RowHeader As String = "Numbers on Mission"
Dim ArrNum As Variant
ArrNum = Split(Replace(Range("A1"), RowHeader, ""), " ")
For i = 1 To UBound(ArrNum)
Cells(1, i + 2) = ArrNum(i)
Next
Cells(1, 2) = RowHeader
End Sub
The same logic is applicable to your second case. Hope this may help.
Unless I'm overlooking something, you may not need VBA at all. Have you tried the "Text to Columns" option? If you select the cell(s) with the information you would like to split up, and go to Data -> Text to Columns. There, you can choose "delimited" and choose a space as a delimiter, which will split your data into multiple cells, split by where the space is.
edit: Just realized that will also split up your string. In that case, when you are in 3rd part of the Text to Columns, choose a destaination cell that isn't the cell with your data. (I.E. if your data is in A1, choose B1 as destination, and it'll put the split info there. Then just combine the text columns with something like =B1&" "&C1&" "&D1)
I was able to properly split the values using the following:
If i.Value Like "*on Mission*" Then
x = Split(i, " ")
For y = 0 To UBound(x)
i.Offset(0, y + 1).Value = x(y)
Next y
End If

text to columns: split at the first number in the value

I have 1 column with about 60 cells with values or different length. Each (or at least most) of the values have a numeric characters in the value. I want to split the columns cells into more columns which I normally would do with the 'tekst to columns' function of excel.
But this function does not have an advanced option of splitting the value at the first numeric character. splitting based on spaces, comma etc. is possible but this does not help me.
Is there any way to divide the cells into 2 columns at the first number in the cell value?
I have looked at numerous other questions but none of them (or other internet fora) have helped me to split the value at the first number of the cell value.
Thanks #quantum285 for the answer. This routine works if the string contains one number. I changed the teststring to firstpart323secondpart.
then part1 returns 'firstpart32' and part2 return secondpart.
I tried to understand what happens in this code, please correct me if I'm wrong:
First, the lenght of the string is determined.
Secondly, for each position in this string is checked if it is numeric or not. But this check is dan from right to left? So in case of firstpart323secondpart: the length is 22.
then isnumeric() checks for every position from 1 to 22 if it is numeric and stops when it finds a number?
If so, part 1 is the the tekst before the value i, where i is the first position from right to left in the string where a number is found.
and part 2 is then the string on the right from this same position.
However, I am looking for a routine which find the first position from left to right (or the last position from right to left) where a number is, ...
So I changed the routine now, simply adjusting the for i = 1 to line:
Sub test()
For j = 4 To Cells(Rows.Count, 4).End(xlUp).Row
For i = Len(Cells(j, 4)) To 1 Step -1
If IsNumeric(Mid(Cells(j, 4), i, 1)) Then
Cells(j, 5) = Left(Cells(j, 4), i - 1)
Cells(j, 6) = (Right(Cells(j, 4), Len(Cells(j, 4)) - i + 1))
End If
Next i
Next j
End Sub
this almost perfectly works (except for a few cells which have multiple number combinations in the value (like: soup 10g 20boxes). But as these are only a few, I can adjust them by hand.
Thanks!
Sub test()
testString = "firstpart3secondpart"
For i = 1 To Len(testString)
If IsNumeric(Mid(testString, i, 1)) Then
part1 = Left(testString, i - 1)
part2 = (Right(testString, Len(testString) - i))
End If
Next i
MsgBox (part1)
MsgBox (part2)
End Sub
Use something like this within your loop.

How to get excel to display a certain number of significant figures?

I am using excel and i want to display a value to a certain number of significant figures.
I tried using the following equation
=ROUND(value,sigfigs-1-INT(LOG10(ABS(value))))
with value replaced by the number I am using and sigfigs replaced with the number of significant figures I want.
This formula works sometimes, but other times it doesn't.
For instance, the value 18.036, will change to 18, which has 2 significant figures. The way around this is to change the source formatting to retain 1 decimal place. But that can introduce an extra significant figure. For instance, if the result was 182 and then the decimal place made it change to 182.0, now I would have 4 sig figs instead of 3.
How do I get excel to set the number of sig figs for me so I don't have to figure it out manually?
The formula (A2 contains the value and B2 sigfigs)
=ROUND(A2/10^(INT(LOG10(A2))+1),B2)*10^(INT(LOG10(A2))+1)
may give you the number you want, say, in C2. But if the last digit is zero, then it will not be shown with a General format. You have then to apply a number format specific for that combination (value,sigfigs), and that is via VBA. The following should work. You have to pass three parameters (val,sigd,trg), trg is the target cell to format, where you already have the number you want.
Sub fmt(val As Range, sigd As Range, trg As Range)
Dim fmtstr As String, fmtstrfrac As String
Dim nint As Integer, nfrac As Integer
nint = Int(Log(val) / Log(10)) + 1
nfrac = sigd - nint
If (sigd - nint) > 0 Then
'fmtstrfrac = "." & WorksheetFunction.Rept("0", nfrac)
fmtstrfrac = "." & String(nfrac, "0")
Else
fmtstrfrac = ""
End If
'fmtstr = WorksheetFunction.Rept("0", nint) & fmtstrfrac
fmtstr = String(nint, "0") & fmtstrfrac
trg.NumberFormat = fmtstr
End Sub
If you don't mind having a string instead of a number, then you can get the format string (in, say, D2) as
=REPT("0",INT(LOG10(A2))+1)&IF(B2-(INT(LOG10(A2))+1)>0,"."&REPT("0",B2-(INT(LOG10(A2))+1)),"")
(this replicates the VBA code) and then use (in, say, E2)
=TEXT(C2,D2).
where cell C2 still has the formula above. You may use cell E2 for visualization purposes, and the number obtained in C2 for other math, if needed.
WARNING: crazy-long excel formula ahead
I was also looking to work with significant figures and I was unable to use VBA as the spreadsheets can't support them. I went to this question/answer and many other sites but all the answers don't seem to deal with all numbers all the time. I was interested in the accepted answer and it got close but as soon as my numbers were < 0.1 I got a #value! error. I'm sure I could have fixed it but I was already down a path and just pressed on.
Problem:
I needed to report a variable number of significant figures in positive and negative mode with numbers from 10^-5 to 10^5. Also, according to the client (and to purple math), if a value of 100 was supplied and was accurate to +/- 1 and we wish to present with 3 sig figs the answer should be '100.' so I included that as well.
Solution:
My solution is for an excel formula that returns the text value with required significant figures for positive and negative numbers.
It's long, but appears to generate the correct results according to my testing (outlined below) regardless of number and significant figures requested. I'm sure it can be simplified but that isn't currently in scope. If anyone wants to suggest a simplification, please leave me a comment!
=TEXT(IF(A1<0,"-","")&LEFT(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00"),sigfigs+1)*10^FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1),(""&(IF(OR(AND(FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1)+1=sigfigs,RIGHT(LEFT(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00"),sigfigs+1)*10^FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1),1)="0"),LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00"))<=sigfigs-1),"0.","#")&REPT("0",IF(sigfigs-1-(FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1))>0,sigfigs-1-(FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1)),0)))))
Note: I have a named range called "sigfigs" and my numbers start in cell A1
Test Results:
I've tested it against the wikipedia list of examples and my own examples so far in positive and negative. I've also tested with a few values that gave me issues early on and all seem to produce the correct results.
I've also tested with a few values that gave me issues early on and all seem to produce the correct results now.
3 Sig Figs Test
99.99 -> 100.
99.9 -> 99.9
100 -> 100.
101 -> 101
Notes:
Treating Negative Numbers
To Treat Negative Numbers, I have included a concatenation with a negative sign if less than 0 and use the absolute value for all other work.
Method of construction:
It was initially divided into about 6 columns in excel that performed the various steps and at the end I merged all of the steps into one formula above.
Use scientific notation, say if you have 180000 and you need 4 sigfigs the only way is to type as 1.800x10^5
I added to your formula so it also automatically displays the correct number of decimal places. In the formula below, replace the digit "2" with the number of decimal places that you want, which means you would need to make four replacements. Here is the updated formula:
=TEXT(ROUND(A1,2-1-INT(LOG10(ABS(A1)))),"0"&IF(INT(LOG10(ABS(ROUND(A1,2-1-INT(LOG10(ABS(A1)))))))<1,"."&REPT("0",2-1-INT(LOG10(ABS(ROUND(A1,2-1-INT(LOG10(ABS(A1)))))))),""))
For example, if cell A1 had the value =1/3000, which is 0.000333333.., the above formula as-written outputs 0.00033.
This is an old question, but I've modified sancho.s' VBA code so that it's a function that takes two arguments: 1) the number you want to display with appropriate sig figs (val), and 2) the number of sig figs (sigd). You can save this as an add-in function in excel for use as a normal function:
Public Function sigFig(val As Range, sigd As Range)
Dim nint As Integer
Dim nfrac As Integer
Dim raisedPower As Double
Dim roundVal As Double
Dim fmtstr As String
Dim fmtstrfrac As String
nint = Int(Log(val) / Log(10)) + 1
nfrac = sigd - nint
raisedPower = 10 ^ (nint)
roundVal = Round(val / raisedPower, sigd) * raisedPower
If (sigd - nint) > 0 Then
fmtstrfrac = "." & String(nfrac, "0")
Else
fmtstrfrac = ""
End If
If nint <= 0 Then
fmtstr = String(1, "0") & fmtstrfrac
Else
fmtstr = String(nint, "0") & fmtstrfrac
End If
sigFig = Format(roundVal, fmtstr)
End Function
It seems to work in all the use cases I've tried so far.
Rounding to significant digits is one thing... addressed above. Formatting to a specific number of digits is another... and I'll post it here for those of you trying to do what I was and ended up here (as I will likely do again in the future)...
Example to display four digits:
.
Use Home > Styles > Conditional Formatting
New Rule > Format only cells that contain
Cell Value > between > -10 > 10 > Format Number 3 decimal places
New Rule > Format only cells that contain
Cell Value > between > -100 > 100 > Format Number 2 decimal places
New Rule > Format only cells that contain
Cell Value > between > -1000 > 1000 > Format Number 1 decimal place
New Rule > Format only cells that contain
Cell Value > not between > -1000 > 1000 > Format Number 0 decimal places
.
Be sure these are in this order and check all of the "Stop If True" boxes.
The formula below works fine. The number of significant figures is set in the first text formula. 0.00 and 4 for 3sf, 0.0 and 3 for 2sf, 0.0000 and 6 for 5sf, etc.
=(LEFT((TEXT(A1,"0.00E+000")),4))*POWER(10,
(RIGHT((TEXT(A1,"0.00E+000")),4)))
The formula is valid for E+/-999, if you have a number beyond this increase the number of the last three zeros, and change the second 4 to the number of zeros +1.
Note that the values displayed are rounded to the significant figures, and should by used for display/output only. If you are doing further calcs, use the original value in A1 to avoid propagating minor errors.
As a very simple display measure, without having to use the rounding function, you can simply change the format of the number and remove 3 significant figures by adding a decimal point after the number.
I.e. #,###. would show the numbers in thousands. #,###.. shows the numbers in millions.
Hope this helps
You could try custom formatting instead.
Here's a crash course: https://support.office.com/en-nz/article/Create-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4?ui=en-US&rs=en-NZ&ad=NZ.
For three significant figures, I type this in the custom type box:
[>100]##.0;[<=100]#,##0
You could try
=ROUND(value,sigfigs-(1+INT(LOG10(ABS(value)))))
value :: The number you wish to round.
sigfigs :: The number of significant figures you want to round to.

Resources