-1

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,

MBrann
  • 223
  • 5
  • 23
  • You need to cast your strings as numeric e.g. try `CINT(ME.VALUE)` if these are integers or `CLNG(ME.VALUE)` if they have decimal places – MiguelH Jun 21 '17 at 15:50
  • @MiguelH Thanks, not sure why I didn't think of that. Excellent thanks for the answer – MBrann Jun 21 '17 at 15:54
  • You might also be interested in this ..http://www.ozgrid.com/VBA/validate-numbers.htm – MiguelH Jun 21 '17 at 15:56
  • @MiguelH `CLng` converts to a `Long`, which is a 32-bit integer type (i.e. doesn't have decimals). If you need decimals you use `CDec` to get a `Decimal`, `CDbl` to get a `Double`, or `CSng` to get a `Single`, keeping in mind that floating-point rounding errors are more likely on `Single` and `Double` types, depending on what you end up doing with the converted numbers. – Mathieu Guindon Jun 21 '17 at 16:08
  • @Mat'sMug oops! .. a little a bit of PEBCAK on my part! Of course it is 'CDec' :-) – MiguelH Jun 22 '17 at 07:39

1 Answers1

2

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.

Graham
  • 7,431
  • 18
  • 59
  • 84
Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235