VB.NET - Can't get Integer to work - vb.net

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)

Related

How to change VBA array decimal separator?

I would like to change VBA array decimal separator to dot. I see it as comma. I tried: Application.DecimalSeparator="."
But when I get the value as MyString = matrix(2, 1), the decimal separator in VBA arrays maliciously persists as comma. I am not able to get rid of the pest.
Is there a way to detect which system separator for VBA arrays is used?
VBA uses quite a few bits drawn from various parts of the platform to work out which decimal and thousands separator to use. Application.DecimalSeparator changes a few instances (mostly on the workbook); you can tweak others at the OS level, but even then though you get to a couple of cases where you can't change the settings.
Your best bet is to write a simple function to check which separator your platform uses based on a trial conversion of say 1.2 to a string and see what the second character ends up being. Crude but strangely beautiful.
Armed with that you can force an interchange of . and , as appropriate. Naturally then though you will have to manage all string to number parsing yourself, with some care.
Personally though I think this is epitomises an unnecessary fight with your system settings. Therefore I would leave everything as it is; grin and bear it in other words.
You have to change it in system settings, Excel takes this kind of settings from system.
I have end up with this function which does exactly what I want. Thank you all for answers, comments and hints.
Function GetVBAdecimalSep()
Dim a(0) As Variant
a(0) = 1 / 2
GetVBAdecimalSep = Mid(a(0), 2, 1)
End Function

Values not calculating in Userform

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.

input string is not in the correct format - double type

I have two text boxes that have double value and i need to calculate the yield. I have changed the code to use Double.Parse now and i am still getting the same result. Attached image shows the error and my run time value. x and y place holder variables have my values. What am i missing here?
Dim FinalProdWt as Double = 0.0
Dim TargetWt as Double = 0.0
Double.Parse(txtFinalProdWt.Text, FinalProdWt)
I am getting "input string was not in correct format" exception. I have been using vb.net after a long time (13 years) and i can't replicate the issue in sample C# code.
You're calling Double.Parse like it was Double.TryParse. That code should be:
FinalProductWt = Double.Parse(txtFinalProductWt.Text)
You must have Option Strict Off or you'd have been warned that your second argument was not the correct type. Turn Option Strict On and leave it On.
I was actually thinking when I first looked at the code that you really should be calling TryParse rather than Parse, so maybe your mistake was actually calling the wrong method rather than passing the wrong arguments.

VBA Inputbox strips decimal comma, converts double to string

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.

When to use CDbl and CStr functions using Visual Basic

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))