Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

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

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 bigger than 500*100.

sub add()
    'This will cause an overflow error
    cells(1,1) = 500 * 100
    'But this won't
    cells(2,2) = 50000 * 100
end sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...