I'm trying to create an Inputbox which has a number, with decimals, as the default value. I'm setting the Inputbox to the formula type, because the user might input a formula or reference a cell.
The problem is that the Inputbox seems to strip the comma and coerse the number to a string. I could fix this casting the number as a string with Format, and then going back to a number afterwards, but losing precision. And I'd like to understand what's going on.
The code is:
Sub test()
Dim Defolt As Double
Defolt = 1.1866701960364
Dim InputValue
InputValue = Application.InputBox("Value?", , Defolt, , , , , 0)
'for this example, the user just clicks OK to the default value
Debug.Print InputValue
End Sub
The results are these:
Thanks!
ps: the locale is Spanish. Excel version is Excel 2010 32bits.
Have a look here. The important part is right under the table:
You can use the sum of the allowable values for Type. For example, for an input box that can accept both text and numbers, set Type to 1 + 2.
and a little further down in the remarks:
If Type is 0, InputBox returns the formula in the form of text — for example, "=2*PI()/360". If there are any references in the formula, they are returned as A1-style references. (Use ConvertFormula to convert between reference styles.)
Try setting the type as 1 and see if you can still use a formula and number. The documentation leads me to think that you can (basically you get formula for free). Since you're setting the type to 0, you're getting back the default Text type.
Related
I'm working with Windows Forms Application in Visual Studio 2015, using .NET Framework 4.5.2. So I'm making a simple program which includes a label to display a value. The label (called lblMoney) displays the currency (in this case, $) and then the value (e.g 350). Together it looks like $350.
Now, I made another form with a textbox called txtCash and a button called bApply. You enter any integer (e.g 350) into txtCash. When you press bApply, the number in txtCash will add to the number in lblMoney. So, if you had 5 in lblMoney, and you entered 350 in txtCash, lblMoney would display 355.
Here's my code to add to the number:
My.Forms.VeilSideCash.lblMoney.Text = cstrx + txtCash.Text.ToString
The form VeilSideCash is the form that holds lblMoney.
Here's the code for cstrx:
Dim cstrx = "$" & Val(My.Settings.Money.ToString)
The problem here is that, instead of overwriting to lblMoney, the new number is just added after the original number. So if lblMoney has 5 and you enter 350 into txtCash, lblMoney looks like $5350.
How would I go about overwriting with the new number (adding to) instead of replacing?
Any help would be appreciated. Feel free to edit incase I messed something up while explaining.
The problem with your code is the Option Strict setting for your project. You have it set to Off and this allows your code to freely treat strings as they were numbers and try to use them in mathematical operations.
But, when you use the + operator between two strings, it doesn't matter if, for a human being, the two strings represent a number, the compiler see them as strings (cstrx, txtCash.Text) and thinks that you want to use the concatenation operator defined for strings (the +). Yielding wrong (for you) results .
I really suggest you to not use the automatic conversions made by the compiler on your code, instead, when you need to do math operations, always convert your strings to numbers and do the math with variables of numeric type (You could also change the Option Strict to On, but you should be prepared to solve a lot of problems in your current code)
Instead, with a proper numeric approach, you get the text inside txtCash and try to check if your user has correctly typed a decimal value.
Dim cash As Decimal
if Not decimal.TryParse(txtCash.Text, cash) Then
MessageBox.Show("Invalid cash value")
Return
End if
Now get the text of lblMoney and convert it back to a decimal number alerting the compiler that there is a currency symbol in the text to convert
Dim current As Decimal
current = decimal.Parse(lblMoney.Text, NumberStyles.Currency, CultureInfo.CurrentCulture)
Now you have two numbers and the + operator does what you expect. It adds the two numbers together. Finally you could write back the result with a proper currency formatting
Dim result as Decimal
result = current + cash
lblMoney.Text = result.ToString("C")
You need to remove the "$" and convert to a number. I used a decimal so you can include cents if you want:
Dim sum As Decimal
sum = Val(cstrx.Replace("$","")) + Val(txtCash.Text)
My.Forms.VeilSideCash.lblMoney.Text = sum.ToString()
Dim cstrx = sum.ToString("C")
Note that I used the "C" to format the sum as currency. That automatically puts the $ on for you, or uses other currency symbols for other countries.
I'm not a big VB.net user, so my syntax may be slightly off.
When you use the + operator with string unexpected results can occur. In this case the string with a $ cannot be implicitly converted so you should explicit convert it
Once you convert your strings to a number type you can then use the + operator and they can be implicitly converted back to a string.
My.Forms.VeilSideCash.lblMoney.Text = decimal.Parse(cstrx, NumberStyles.Currency)
+ decimal.Parse(txtCash.Text ,NumberStyles.Currency)
Cell A1 contains the number 25, which is right-aligned, implying it's a number, not text.
D1 contains the formula:
="" & A1
The 25 in D1 is left-aligned, implying it's text. That is confirmed by the following formula, which returns 1:
=IF(D1="25",1,0)
The following VBA code puts 25 in F1 but the 25 is right-aligned and the IF test returns 0:
Range("F1") = "" & Range("A1")
Any explanation for the discrepancy?
E1 contains the following formula which gives a left-aligned 25 and the IF test returns 1:
TEXT(A1,"0")
However, the following code gives a right-aligned 25 and the IF test returns 0:
Range("F1") = Application.WorksheetFunction.Text(Range("A1"), "0")
Not that I have to use the TEXT function. I just wonder why it works differently than when in a worksheet.
Any rule that tells when or what worksheet functions won't work in VBA code, or more precisely, will give different results than when in worksheet?
When a data is written by vba into a cell, an internal type conversion function is called if required, that is if the data type is different from the cell's numberformat property.
You dont want that conversion function to be called.
To avoid this conversion function to be called, choose the proper Numberformat property for the cell before writing the data.
Range("b4").NumberFormat = "#"
Range("b4") = Application.WorksheetFunction.Text(Range("A1"), "0")
You simply get the wrong idea of what is a number in Excel.
in general ALL input is a string. Also writing "25" in a cell.
However: If possible, Excel will convert all inputs to a numerical value if possible. Also for dates and times.
To prevent this, you simply insert a ' in front of your "text" in the cell.
The confusing part for you is the different behavior for formulas.
A formula will always output a "result" AND the "data type".
So =1+1 will be numeric as the last action was math.
=Left(1+1,1) will be text as the last action was text-based.
For =A1 it will simply copy the type. If there is a formula, then this will be the same. But if there is a "direct input" it will always try to convert to numerical and only be text if it can't be converted or if it starts with a leading ' (A1 itself does this already).
As a result: If there is a plain 25 in the cell, it will always be "numerical" no matter "how" you input the 25.
For newer Excel there is only one exception: if the cell formatting is text prior to entering a number, it will be treated as text (no converting). This does not apply if you change the formatting later.
Simple test:
enter 25 in A1 (formatting general)
enter =ISNUMBER(A1) in A2 (will be TRUE)
set formatting for A1 to "text" (A2 will still be TRUE)
enter 25 in A1 (now A2 will become FALSE)
This may fail (Excel confuses itself sometimes here). Try it with a new sheet. ;)
Hopefully you understood the fault in your logic ;)
The cell alignment says nothing about the cell's contents. Forget about anything being "implied" by it. When you start on a virgin worksheet the format for all cells is "General" which means that Excel will decide the format of what you enter. If you enter a number the format will be "Number". If you enter what looks like a date to Excel the format will be "Date", and for most other things the format will be "Text".
So, if you enter " 25" in a cell formatted as "General" Excel will recognise this to be a number despite the leading spaces, read it is numeric, and format the cell to the right. This will happen regardless of whether you made the entry by hand or used VBA. You can then proceed to format the alignment as you wish.
However, if you enter the number 25 in a cell formatted as Text Excel will recognise the number as text and display it formatted to the left (unless you expressly formatted the horizontal alignment to the right).
The best way to deal with any problems you might encounter in this regard, set the NumberFormat and HorizontalAlignment properties for the cells that you want to write to. You can do that both manually or using VBA.
Worksheet function when used in the worksheet behaves / works the same way as when used in VBA. Consider below code:
Note: Range("B1") contains a numeric value 25
Dim r As Range, v As Variant
Dim wf As WorksheetFunction: Set wf = Application.WorksheetFunction
With Sheet1
Set r = .Range("B1")
v = r.Value2
v = wf.Text(r.Value2, "0")
End With
Now using the local window, let us check the data type of variant v.
SC1: All variables un-initialized
You can see, at the start that all variables have no value and the variant type v is empty.
SC2: Variables initialized and v assigned a value
After executing lines up to v = r.value2, all variable types were confirmed (e.g. Range/Range etc.) and variant v is now Variant/Double.
SC3: Re-assign a value on v but using worksheet function Text
Executing the last line which uses the worksheet function Text, variant v type becomes Variant/String. I think this confirms that the function Text works as expected converting the numeric 25 into a string type.
As for the behavior of passing VBA generated value to worksheet, it is covered by Docmarti's post above.
I have an issue with vba macros. Cell contains value 941144280284022000000. But when try to get this value in macros, variable is equal
9.41144280284022E+20. Is it possible to get "real" value?
Thanks.
Here is an example:
Sub dural()
MsgBox ActiveCell.Text
End Sub
This will insure that long strings of numerals are not converted to numbers.
EDIT#1:
This assumes that the cell actually displays the long string of numerals. If the cell displays ####, that is what the sub will pick-up. If the cell displays 9.41E+20, then that is what my sub will pick-up.
My sub will not necessarily pick-up the contents of the Formula Bar.
Try a simple :
Dim myVar as Variant
myVar = CDec(Range("A1").Value)
If you wish to store a value that looks like a number (or is a number) but has more than 15 digits of precision, then you must either format the cell as text before entering the value, or prepend the value with a single apostrophe to indicate to Excel that the value is to be treated as text and not a number.
If you don't do this, then as soon as the value is entered, there's a good chance it will be altered by Excel. The trailing zeros in the example value mean this does not happen in this specific case, but try changing that last 0 to 1 and you'll see what I mean.
You enter: 941144280284022000001
Excel converts this to: 941144280284022000000
More reading: https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel
I have a user input box where you type in a string, annoyingly this string looks like a date 00/00/0000 and excel reformats it as such.
When the value can't be a date ex. 18/19/4561 (month can't be 18 or 19) it displays it correctly.
But whenever it can be seen as a possible date it switches things around.
I've tried setting the value as a string rather than nothing but excel still changes it when putting it in the page.
When I try manually inputting it in the cell or equal the values from a manually entered cell it works fine.
But whenever I get it from the inputbox it messes with it. Even when I hard code the string to a variable (x = "05/06/4564") it switches things around.
How do I force excel to leave the string as is?
Prefix the value with a single apostrophe and Excel will interpret it as a string.
Eg '18/19/4561
Also, have you tried setting the cell format to Text
I've been looking up in Google in these past days but I still can't find a good answer to this one.
Currently, this is how I do it:
For Each cell In ws.Range(fromCol, toCol)
If IsNothing(cell.Value) Then Exit For
valueList.Push(cell.Value.ToString())
Next
But when it reads a cell whose assumed data type is Time, it returns a Double value. I try to parse that value but it's not the same as expected.
How can I properly read a single Excel cell with an assumed type of Time?
As per the comment suggesting the article,
.Text is a bad idea in the sense that it will give you just the displayed string in that cell. If you use TypeName on the cell's content, for example, it will always return string regardless of any datatypes the content might be. However, if you use .Value, it will return the actual datatype name of the content of that cell.
This can prove useful to you if you're using TypeName in a comparison for instance. It saves you using conversion functions.
Take this example:
Sub Test()
Range("A1") = "True"
Debug.print(TypeName(Range("A1").Value))
Debug.print(TypeName(Range("A1").Text))
End Sub
This Output is:
Boolean
String