问题描述
我们编写了一个生成大量图表的宏,然后将它们传输到Word。当Excel 2007中访问这样的形状时,这可以像预期的那样工作:
形状(0)...但是在Excel 2010中,我们不得不说:形状(1)。有没有办法告诉Excel从0开始计数?
这是一个明亮的微软工程师的决定的宿醉使VB集合索引开始于1.我认为这是VB4的设计时。
正当的理由是,索引从1到N运行是更容易而不是0到N-1。
因此,包括Excel在内的许多COM对象模型都遵循此模型,因此像工作表,形状等集合都从1对于您在Excel 2007中的预期,Shapes(0)的工作原理,我感到非常惊讶。它肯定没有在Excel 2003中,而且似乎不太可能这将被更改。
更新
Excel 2007和Shapes(0)确实引用了集合中的第一个Shape,就像我们可以看到的Shapes(1)一样。这是Excel 2003和Excel 2007之间的变化,我找不到任何信息 - 我怀疑它是Excel 2007中的一个错误。
从你说的话,听起来像Excel 2010已经恢复到与Excel 2003相同的行为(即Excel 2007错误已经修复)。如果您希望在所有版本的Excel中使用代码,请使用1到N的索引号。
We have written a macro that generates a host of charts and then transfers them to Word. This works as expected in Excel 2007, when accessing shapes like this:Shapes(0)... But in Excel 2010 we had to say: Shapes(1). Is there a way of telling Excel to start counting from 0?
This is a hangover from a decision by some bright Microsoft Engineer to make VB collection indexes start with 1. I think this was when VB4 was designed.
The justification was that it is "easier" to have indexes running from 1 to N rather than 0 to N-1.
As a result, many COM object models including Excel follow this model, so that collections like Worksheets, Shapes etc are all indexed from 1 to N.
I am surprised at your assertion that Shapes(0) worked as expected in Excel 2007. It certainly didn't in Excel 2003, and it seems unlikely that this would have been changed.
Update
I've tested this in Excel 2007 and Shapes(0) does indeed reference the first Shape in the collection - the same as Shapes(1) as far as I can see. This is a change between Excel 2003 and Excel 2007 for which I can't find any information - I would suspect it's a bug in Excel 2007.
From what you say, it sounds like Excel 2010 has reverted to the same behaviour as Excel 2003 (i.e. the Excel 2007 bug has been fixed). If you want code that works in all versions of Excel, use index numbers from 1 to N.
这篇关于如何使Excel中的VBA从0开始计数,而不是1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!