Values not calculating in Userform

2019-09-19 17:20发布

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,

1条回答
男人必须洒脱
2楼-- · 2019-09-19 17:59

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.

查看更多
登录 后发表回答