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

前端 未结 4 1434
心在旅途
心在旅途 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 02:54

    Consider:

    Sub add()
        'This works:
        Cells(1, 1) = CLng(500) * 100
        'as does this:
        Cells(2, 2) = 50000 * 100
    End Sub
    

    Evidently VBA was picking a default type of Integer for the first expression because that type is large enough to hold the literals on the right hand side. 50000 is too big for an Integer so it interprets it as a Long. CLng explicitly triggers a promotion to Long.

提交回复
热议问题