Why cells(1,1) = 500 * 100 causes overflow but 50000*100 doesn't?

前端 未结 4 1435
心在旅途
心在旅途 2020-12-15 02:29

I just created a simple sub and it gives an overflow error. However, I don\'t see anything wrong with the code, and it is really weird since 50000*100 is much b

4条回答
  •  隐瞒了意图╮
    2020-12-15 03:09

    This is because of how VBA evaluates mathematical expressions. The return type of expression will be the type of first operand in the expression or its nearest numeric type equivalent. However, the final result may not fit in that return type and throw overflow error.

    When you do 500*100 , return type is integer. While when you do 50000*100 the return type of this expression is Long.

    To avoid overflow error you can do an explicit cast to let it know your intentions

    CLng(500) * 100

提交回复
热议问题