以十六进制和十进制设置颜色的行为不同 [英] Setting colors in Hex and Decimal behaving differently

查看:246
本文介绍了以十六进制和十进制设置颜色的行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  WorkSheet.Range(A1:A5)。Interior.color =& HC0FF'十六进制值49407 

这两个不是完全相同吗?
正在设置的颜色是不同的。

解决方案

不,这些值不等效: & HC0FF 是-16129,而 & HC0FF& 是49407.



VBA是一种较旧的语言,默认情况下使用16位整数。在这个时代,你几乎想要长久而不是ints,但你必须要求VBA。



& HC0FF 是一个从十六进制定义16位常量的结构。因为此值中的符号位被设置为(接通,消极),当解释为16位值时,因此转换为-16129。我们可能会认为这是吸吮,但它不是一个错误!当使用-16129(作为有符号整数),以32位形式,1通过整个前16位传播,并导致蓝色值为255。



你真正想要的是一个32位十六进制常量:& HC0FF&
额外的$ code& 告诉VBA这是一个长常量而不是int。解释为32位,这是一个正值,所以给出你正在寻找的十进制等价物。



简而言之,要求长十六进制常量, code>& 。



另外,VBA对16位的倾向也可以在使用十进制常数时咬我们,如表达式16000 * 16000,将溢出16位运算。所以有时需要使用十进制常量尾随的& (或者先分配一个到前一个)。


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

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

and

WorkSheet.Range("A1:A5").Interior.color = &HC0FF 'Hex value of 49407

Aren't these two supposed to be exactly equivalent? The colors being set are different.

解决方案

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).

这篇关于以十六进制和十进制设置颜色的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆