Results 1 to 4 of 4
  1. #1
    New Lounger
    Join Date
    Feb 2003
    Location
    Kikinda, Serbia and Montenegro (Yugoslavia)
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Weird behavior of Long type (VBA in Office 2003/2007)

    I have just been making some quick tests on VBA behavior on Excel 2007 '65535' bug, making this trivial macro:

    Sub test()

    Dim x As Double
    Dim a As Double
    Dim b As Double

    a = 850
    b = 77.1
    x = a * b
    Debug.Print x

    End Sub

    Result is correct (65535), as the most of you might already know, giving you followed all informations on recent bug.

    Now, I was playing a little bit with data types and witnessed this - if you change type of b to Long:

    Dim b As Long

    result will be 65450!

    I've tried this in several Office 2003 and Office 2007 programs.

    Now, I might have missed something regarding data types, but this distortion leaves me speechless.

    Any comment? Did I really missed some warnings in VBA manuals?

  2. #2
    Plutonium Lounger
    Join Date
    Mar 2002
    Posts
    84,353
    Thanks
    0
    Thanked 29 Times in 29 Posts

    Re: Weird behavior of Long type (VBA in Office 2003/2007)

    The result that you get is correct. The Long data type is for whole numbers. If you use

    Dim b As Long
    b = 77.1

    you are in fact setting b to the whole number 77. The decimal part .1 is ignored.
    If you calculate 850 * 77 on paper or using a calculator, you'll find that the product is 65450 - exactly the value that VBA displays.

  3. #3
    New Lounger
    Join Date
    Feb 2003
    Location
    Kikinda, Serbia and Montenegro (Yugoslavia)
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Weird behavior of Long type (VBA in Office 2003/2007)

    Well, that's it - I *did* missed something in VBA manuals...

    Interesting that b = 77.1 doesn't make an err.

    Thanks for the quick reply!

  4. #4
    Plutonium Lounger
    Join Date
    Mar 2002
    Posts
    84,353
    Thanks
    0
    Thanked 29 Times in 29 Posts

    Re: Weird behavior of Long type (VBA in Office 2003/2007)

    VBA is very forgiving - if you assign a value of type A to a variable of type B, it will do its best to fit the value into type B. You only get an error message if that is not possible.

    Examples: say you have declared two variables:

    Dim a As Long
    Dim b As String

    The instructions

    a = 37
    b = a

    will result in b containing the string "37".

    The instructions

    b = "345"
    a = b

    will result in a containing the number 345.

    The instructions

    b = "Dragan"
    a = b

    will result in error 13 (type mismatch) because VBA cannot convert "Dragan" into a number.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •