简体   繁体   English

如何使用Excel 2007 VBA在每列的多行/列范围上循环?

[英]How to loop over a multi-row/column range per column using Excel 2007 VBA?

I'm looping to loop over a range with multiple rows and columns using Excel 2007 VBA. 我循环使用Excel 2007 VBA遍历具有多个行和列的范围。

I'm specifically trying to loop over a user selected range, and perform a calculation on each column in the range, and output the calculation two rows below each column. 我专门尝试遍历用户选择的范围,并对范围内的每一列执行计算,并在每一列下方输出两行。

You can retrieve the currently selected range by using 您可以使用来检索当前选择的范围

Application.Selection.Address

This will give you a range value (the Selection property returns a Range object) that will look something like " $B$4:$J$20 ". 这将为您提供一个范围值(Selection属性返回一个Range对象),该范围值看起来像“ $B$4:$J$20 ”。

Given you now have a range to work with, you can iterate across each column using something like: 既然您现在可以使用一个范围,则可以使用类似以下内容的方法遍历每列:

For Each col In userSelectedRange.Columns

   ...

Next

The Columns property again returns a Range object that you can either iterate over further or perform other calculations on (your exact needs aren't too clear from your question). Columns属性再次返回一个Range对象,您可以对其进行进一步迭代或对其进行其他计算(您的确切需求对您的问题不太清楚)。

To post the calculated result two rows above each column (eg a subtotal or similar), try using the Offset function: 要将计算结果过帐到每列上方两行(例如小计或类似结果),请尝试使用偏移功能:

Cells.Offset(-2, 0)

If you're able to provide more specifics around the sort of calculation you want, I may be able to add more detail into how you achieve it. 如果您能够围绕所需的计算类型提供更多详细信息,我也许可以为您如何实现提供更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM