Setting colors in Hex and Decimal behaving differently

前端 未结 4 1233
攒了一身酷
攒了一身酷 2020-12-31 10:08

I am trying to set an orangish color in the following manner:

WorkSheet.Range(\"A1:A5\").Interior.color = 49407

and

WorkShe         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 10:23

    No, those values are not equivalent: &HC0FF is -16129, whereas &HC0FF& is 49407.

    VBA, being a rather old language uses 16 bit integers by default. In this day and age, you pretty much want longs always instead of ints, but you have to ask VBA for them.

    &HC0FF is a construct that defines a 16-bit constant from hex. Because the sign bit in this value is set (on, negative) when interpreted as a 16-bit value, hence the conversion to -16129. We may consider that this sucks, but it is not a bug! When you use -16129 (as a signed integer), in 32 bit form, 1's are propagated thru the whole top 16 bits and that results in the blue value of 255.

    What you really wanted here is a a 32-bit hex constant: &HC0FF&. The extra & on the end tells VBA that this is a long constant instead of an int. Interpreted in 32-bits, this is a positive value, so gives the decimal equivalent you're looking for.

    In short, ask for long hex constants with the trailing &.

    As an aside, this propensity of VBA toward 16 bit can also bite us when using decimal constants, such as in an expression 16000 * 16000, which will overflow 16 bit arithmetic. So, sometimes one needs to use the trailing & on decimal constants too (or assign one to a long first).

提交回复
热议问题