Can someone please help me.
I have a userform which has a number of numeric fields. The issue is that my Total box will not calculate them as it is recognising a number as text. So for example if I was to say HE.Value (10) + ME.Value (10) for example should = 20 however is the Total is coming to 1010. and if I * it instead I am receiving an error to debug as it recognises the value as text format.
I have never had this issue in a userform before. Is someone able to assist please?
Thanks,
You have:
totalBox.Text = box1.Text + box2.Text
When the two operands are String, the + operator works as a string concatenation operator, meaning it works exactly like the & operator. That's how you get 1010 instead of 20: VBA thinks you're asking it to concatenate strings.
VBA cannot do arithmetics on strings, so if your strings represent numeric values, you need to convert them first.
If you're only working with integers then you can do this with the CLng type conversion function:
totalBox.Text = CStr(CLng(box1.Text) + CLng(box2.Text))
Notice this makes the back-to-string conversion explicit (CStr); leave it out and VBA will perform that type conversion implicitly.
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)
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.
I've been searching for a solution to this for a while and have been unsuccessful in finding. Essentially, I have the user of my document populating fields in a user form that my code then puts into the appropriate cells. One of these input fields is a number but, no matter how I instruct excel to format the cell, it still is text in the end and I can't perform any calculations. I'm sure this is probably a pretty simple fix but I've been unsuccessful so far in finding a solution. As always, any help is appreciated!
thanks!
You need to convert the value from text to a numeric type before putting it into a cell.
Assuming your textbox is called txtNumber and you're outputting to cell Output!A1, the code would be:
Sheets("Output").Range("A1") = CDbl(txtNumber)
Other conversion functions you might want to use are CLng (convert to Long), CInt (convert to Integer), CDec (convert to decimal, useful for currency values).
This code will raise an error if the user types a non-numeric text value into the field. You should validate on the textbox's Change event and disable the OK button if invalid data is inputted.
Why does VBA interpret "093 0005" as a date?
In MS Access VBA, the following line:
Format("093 0005", "0000000000000") returns "0000000034090"
34090 is the vba numeric equivalent of the date 5/1/1993.
In most cases this kind of date assumption does not occur. For example:
Format("092 0250", "0000000000000") returns "092 0250", i.e. does not try to apply formatting.
Format("0930005", "0000000000000") returns "0000000930005" as expected.
The only solution to this that I have come up with so far is to code around using this function when the inbound string contains a space or use the IsDate function.
This has nothing to do with Access per se. In any VBA, the format function will behave like this if the text is either separated by a SPACE, HYPHEN, or a DASH. So this
Debug.Print Format("093 0005", "0000000000000")
Debug.Print Format("093/0005", "0000000000000")
Debug.Print Format("093-0005", "0000000000000")
will return 0000000034090
It will try and convert it to date or a number and if it is a valid date or number then it will show you the numeric equivalent of it. And if it is not a date or number equivalent then it will leave it as it is. I believe the reason for this is that the Format function is unable to ascertain the "Format" of the value and takes it as a string. It is similar to then saying Format("Blah", "0000000000000"). It is but obvious that you will not expect Format function to format it as 000000000blah.
Unfortunately I couldn't find any article in MS knowledge-base which explains why Format function behaves like this.
The only way that I have discovered in the past to get around it is to use the VAL function to convert it to a number. So
Debug.Print Format(Val("093 0005"), "0000000000000")
will give you the desired result 0000000930005
However if the numbers are separated by a HYPHEN or a DASH then the VAL function is useless. For that you will have to use REPLACE to replace the HYPHEN or a DASH with SPACE. However I doubt that you will be formatting numbers which have a HYPHEN or a DASH.
I'm learning to use this program. I'm a few weeks into learning it, and I'm understanding most of it fine, but I just cannot get a grasp on when to use the CDbl, CInt, CStr, etc. functions. Here's an example of a few lines of code I can't get a grasp of:
If IsNumeric(txtFirst.Text) And IsNumeric(txtSecond.Text) Then
txtSum.Text = CStr(CDbl(txtFirst.Text) + CDbl(txtSecond.Text))
This program is supposed to take two numbers that are input by the user and add them together. Simple. I was playing around with it, and I took out the CDbl and CStr functions, and the two numbers that were supposed to be added together were only added side by side (for example, if I input 2 and 15 as my numbers it would spit out 215).
So I'm curious when to use these functions.
How come on the second line, it says CStr(CDbl(? Why would I need to convert to double, THEN to string? Which is my understanding, unless I am reading this wrong.
Another question I have is, if I declare var1 as Dim var1 as Double. I constantly see the next line as var1 = CDbl(txtbox.text) and so on. I don't understand why we need to convert to Double here, since when I declared the variable as a double, it should already be in a double form already, shouldn't it?
The inner CDbl(txtFirst.Text) converts the first textbox's value to a number. The outer CStr(... + ...) converts the whole sum back to a string.
Your variable is declared as a Double, but the Text property is a String.
You need CDbl to convert the string to a number so that it can fit inside the variable.
To understand this code:
txtSum.Text = CStr(CDbl(txtFirst.Text) + CDbl(txtSecond.Text))
Let's separate it into pieces. First of all, value in a textbox control is of String type. In order to perform ADDITION, the string type needs to be converted into double type, so you do CDbl(txtFirst.Text) and CDbl(txtSecond.Text)
The ADDITION operation is done by CDbl(txtFirst.Text) + CDbl(txtSecond.Text). In order to assign the result of that ADDITION to a textbox control, you need to convert it to String type. So you do CStr() on CDbl(txtFirst.Text) + CDbl(txtSecond.Text). So the full operation in one line code is txtSum.Text = CStr(CDbl(txtFirst.Text) + CDbl(txtSecond.Text))