EXCEL VBA: Scientific Notation in a Userform Textbox - excel

I am developing a userform in EXCEL using VBA. One of the default values for a user input in the form is 1E-12. I need to display this in the userform. However, when I initialize the textbox in the form, EXCEL immediately changes the representation of the value to 0.000000000001 (Both in the editor and in the userform when I check it). Computationally, of course, this is not an issue, however, it is a little tough to read for the user (and takes up to much space in the form to display the whole number). Is there a way to force EXCEL to show this value in scientific notation in the userform textbox?
Thanks!
Dan

You can use the VBA.Strings.Format$ function to control the string representation of numbers.
Specifying a "Scientific" format string will sort-of work, but if you need to control the level of precision, you'll need a more elaborate format string. You can make a FormatScientific function to abstract away that complexity:
Public Function FormatScientific(ByVal value as Double, Optional ByVal precision As Long = 6) As String
If precision < 1 Then precision = 1
Dim formatString As String
formatString = "0." & String(precision - 1, "0") & "#e-#"
FormatScientific = Format$(value, formatString)
End Function
Here I made the precision optional parameter be 6 if unspecified; adjust as you see fit.
Now you can invoke FormatScientific(0.0000123456789) and get 1.234568e-5 with a consistent number of significant digits, regardless of what you give it, whereas a "Scientific" format string only gives you 1.23E-05, which loses quite a lot of the significant information.
(adapted from parts of this code)

tbNum.Text = Format(Sheet1.Cells(1, 1).Value, "Scientific")
Takes value in the cell and converts it to scientific notation.

Related

Data extraction from excel with operators is unable to store values

I have a Excel file with two columns. One has a name other has the corresponding mass to it. I have used the corresponding lines to read it and find the position of the name. But when I am trying to find the mass to the corresponding name as shown below it is not able to store it in the memory. In the Excel file, I have the mass values as 1.989*10^30. This seems to affect the code as the same code works fine when the cells in the excel has just numeric values.
majbod = 'Sun';
minbod = 'Earth';
majbodin = readtable("Major_and_Minor_Bodies.xlsx","Sheet",1);
minbodin = readtable("Major_and_Minor_Bodies.xlsx","Sheet",2);
MAJORBODY = table2array(majbodin(:,"Major_Body"));
MINORBODY = table2array(minbodin(:,"Minor_Body"));
mmaj = table2array(majbodin(:,"Mass"));
mmin = table2array(minbodin(:,"Mass"));
selected_majbody = find(strcmp(MAJORBODY,majbod));
selected_minbody = find(strcmp(MINORBODY,minbod));
M = mmaj(selected_majbody);
m = mmin(selected_minbody);
disp([M ;m])
Is there a better way to write the code compared to the way which I wrote?
Thanks.
Excel does it's best to figure out what kind of data is in each cell. Since your data has something besides just numbers, Excel treats it like a string. You have a couple of options for getting around that:
If you put an equals sign in front of it, it will treat it like an equation, and calculate the value of 1.989*10^3 for you. this will be a number.
Since scientific notation is so common, programmers have created a shortcut for representing it. They often use the character 'E' where you use "*10^". This means that if you type "1.989E30", excel will recognize that as a number.
If keeping the current string format is very important, you could probably modify the string during extraction - replace '*10^' with E, and then whatever language you are using will have a string to number parser you can use.
If the real problem is that the real numbers are just too long in Excel, you can always format the cell that they are in. (right click the cell, select format cells, then select scientific.)
Good luck

Excel : Find only Hexa decimals from 1 cell

I'm a newbie on Excel.
So I have a list of some names ending with Hexa decimals. And some names, that doesn't have any.
My mission is to see only those names with Hexa decimals. (Mabye somehow filter them out)
Column:
BFAXSPOINTDEVBAUHOFLAN2AD
BFAXSQLBAUHOFLAN207
BFAXSQLDEVBAUHOFLAN27A
BFREPDEVBAUHOFLAN258
BFREPORTINGBAUHOFLAN20B
COBALTSEA02900
COBALTSEAVHOST900
DIRECTO8000
DIRECTO9000
DIRECTODCDIRECTOLA009
DYNAMAEBSSISE006
SURVEYEBSSISE006
KVMSRV00",
KVMSRV01",
KVMSRV02",
ASR
CACTI
DBSYNC",
DTV
and so on...
The Function HEX2DEC will help you achieve what you want - it attempts to convert a number as a hexidecimal, into a decimal. If it is not a valid Hex input, it will produce an error.
The key is understanding how many digits you expect your decimal to be - is it the last 5 characters; the last 10; etc. Also note that there is a risk that random text / numbers will be seen as hexidecimal when really that's not what it represents [but that's a problem with the question as you have laid it out; going solely based on the text provided, all we can see is whether a particular cell creates a valid Hexidecimal].
The full formula would look like this[assuming your data starts in A1, and that your Hexidecimal numbers are expected to be 6 characters long, this goes in B1 and is copied down]:
=ISERROR(HEX2DEC(RIGHT(A1,6)))
This takes the 6 rightmost characters of a cell, and attempts to convert it from Hex to Decimal. If it fails, it will produce TRUE [because of ISERROR]; if it succeeds, it will produce FALSE.
Then simply filter on your column to see the subset of results you care about.
Consider the following UDF:
Public Function EndsInHex(r As Range) As Boolean
Dim s As String, CH As String
s = r(1).Text
CH = Right(s, 1)
If CH Like "[A-F]" Or CH Like "[0-9]" Then
EndsInHex = True
Else
EndsInHex = False
End If
End Function
For the string to end in a hex, the last character must be a hex.

Conversion from hexadecimal string to Double yields wrong results

I am trying to convert 14 bit hex numbers to decimal.
I have this VBA code.
Option Explicit
Public Function HexadecimalToDecimal(HexValue As String) As Double
Dim ModifiedHexValue As String
ModifiedHexValue = Replace(HexValue, "0x", "&H")
HexadecimalToDecimal = CDec(ModifiedHexValue)
End Function
With numbers like this to convert to decimal
0x047B1142591E80
0x044A81325A1E80
0x047B7542591E80
I keep getting random results across large amounts of data. Sometimes spot on other times the numbers are off by 6 or 2.
Try changing the return type of the function from Double to Variant. Double has only about 15 decimal digits of precision, so can't, for example, capture the value 1261213964639872 (which has 16 digits) exactly. The closest it can get is 1261213964639870. By changing the return type to Variant, the full precision returned by CDec will be preserved. You can't use a Decimal return type, because VBA for some reason does not support this.
The problem isn't with VBA. Excel cells can only hold 15 digits in number format. So the "number" 1234567891234567 will always display 1234567891234560. This can be avoided by converting items to text AND/OR changing the cell format to text.
But this doesn't always work.
The only surefire way to make sure it will retain all digits is to append something onto the string that isn't a number.
This code will append an apostrophe before the number, but return the entire string.
Public Function HexadecimalToDecimal(HexValue As String) As String
Dim ModifiedHexValue As String
ModifiedHexValue = Replace(HexValue, "0x", "&H")
HexadecimalToDecimal = "'" & CDec(ModifiedHexValue)
End Function
Unfortunately, not a perfect solution.

Does Excel's Worksheet Comparison Operator Give Inconsistent Results?

Consider the following. Place =400000000000000/3 in a cell, say "A1". Excel displays 133333333333333.0000. The precision is zero digits to the right of the decimal point because, apparently, Excel's floating point precision is no more than 15 digits. Now place the following formula in a cell:
=A1=ROUND(A1,0)
The formula produces True since there are no digits to the right of the decimal point ... or are there? Open the VBA editor, right click on your Workbook in the Projects pane and insert a VBA module. Define the following UDF:
Function Equals(dblOne As Double, dblTwo As Double) As Boolean
Equals = dblOne = dblTwo
End Function
Now go back to your Worksheet and place the following formula in a cell:
=Equals(A1,ROUND(A1,0))
The result is now False. Why?
Excel's 15 apparent decimal digits of precision are the object of an entire section of William Kahan's essay “How Futile are Mindless Assessments of Roundoff in Floating-Point Computation ?”:
What’s so special about 15 sig. dec.? Displaying at most 15 sig. dec.,
as Excel does, ensures that a number entered with at most 15 sig.
dec., converted to binary floating-point rounded correctly to 53 sig.
bits (which is what Excel’s arithmetic carries), and then displayed
converted back to decimal floating-point rounded correctly to at least
as many sig. dec. as were entered but no more than 15, will always
display exactly the same number as was entered. The decision to make
Excel’s arithmetic seem to be Decimal instead of Binary restricted
Excel’s display to at most 15 sig. dec., thus hiding the deception
well enough to reduce greatly the number of calls upon Excel’s
technical help-desk. When symptoms of the deception are perceived they
are routinely misdiagnosed; e.g., see David Einstein’s column on p. E2
of the San Francisco Chronicle for 16 and 30 May 2005.
The section concludes with:
This is no place to list all the corrections Excel needs. It was cited
here only to exemplify Errors Designed Not To Be Found.
If you run the below code msgbox gives the difference in two values. Hence it returns false.
Function Equals(dblOne As Double, dblTwo As Double) As Boolean
MsgBox dblOne - dblTwo
Equals = dblOne = dblTwo
End Function
Below code will return true
Function Equals(dblOne As Double, dblTwo As Double) As Boolean
Equals = Round(dblOne, 0) = dblTwo
End Function

When putting string that into Excel spreadsheet it puts to Scientific notation or rounds up

I am putting a string into excel. The string is often only numeric digits but can have alpha characters or hypens etc.
When I don't set the number format or set it like this
(Where xlSheet(0) is Excel.Worksheet)
xlSheet(0).Columns("N:N").EntireColumn.Columns.NumberFormat = "#"
It outputs in scientific notation.
When I use this code:
xlSheet(0).Columns("N:N").EntireColumn.Columns.NumberFormat = "0"
It rounds up the number to the nearest 100,000 so that the last five digits are 0's when they shouldn't be.
Should be: 1539648751235678942
But is: 1539648751235600000
The cells that have a hyphen or a letter aren't affected and work fine.
Any help would be greatly appreciated.
EDIT:
I add the data like this:
I loop through and put in xlSheet(0).Cells(i, 14) = rs!value_number
Where rs is my ADODB.Recordset
EDIT2: Herbert Sitz got it by adding an apostrophe before the text! Thanks everyone.
I think problem is that the number you're trying to enter can't be accommodated exactly by Excel. Excel has limitations on what numbers it display/represent because of the way numbers are stored internally. In Excel's case numbers are limited to 15 digit precision (see http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP010073849.aspx ), which is not enough to represent your number.
You can enter the number as a string ("152..42") and all digits will be displayed, but you won't be able to perform exact mathematical operations with it.
For numbers, Excel can only handle 15 significant digits.
If you want to store a number that is more than 15 digits long without losing data, you have to store the data as text.
Doing what you've been doing will resolve the issue:
You can do either of the following to add your numbers as text:
xlSheet(0).Cells(i, 14).Numberformat = "#"
xlSheet(0).Cells(i, 14) = rs!value_number
Or
xlSheet(0).Cells(i, 14) = "'" & rs!value_number

Resources