【问题标题】:Excal macro loop for each element in array数组中每个元素的Excel宏循环
【发布时间】:2014-01-29 18:19:36
【问题描述】:

我有相对大量的数据要放入图表中。

基本上,我拥有的是多个组件(总共 30 个,但在下面的示例中,我将代码限制为 5 个组件),每个组件都有一列。 我已将列号分配给各个组件,声明为整数。 有时我不希望一个组件有一个图表,所以这就是数字存在差距的地方(例如,diat 和 hydr 之间是第 5 列中的另一个组件,但对于这个不应该有图表)。

然后我想将我想要一个图形的所有组件放入一个数组并执行 For... Next 循环,以便为数组中的每个元素自动创建一个图形(因此对于数组中的每个组件)。

显然我做错了什么:-)。当我第一次尝试引用数组中受尊重的元素时,代码卡住了:ActiveChart.SeriesCollection(1).Name = Cells(9, componentlist(1, i))

Dim diat, hydr, para, terb, theo As Integer
diat = 4        'column number of the component named diat
hydr = 6        'column number of the component named hydr
para = 7        'column number of the component named para
terb = 9        'column number of the component named terb
theo = 10       'column number of the component named theo

Dim componentlist As Variant
componentlist = Array(diat, hydr, para, terb, theo)

For i = 1 To UBound(componentlist)

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatterLines
ActiveChart.SeriesCollection.NewSeries.Select
ActiveChart.SeriesCollection(1).Name = Cells(9, componentlist(1, i))
ActiveChart.SeriesCollection(1).XValues = Worksheets(2).Range(Cells(10, 3), Cells(21, 3))
ActiveChart.SeriesCollection(1).Values = Worksheets(2).Range(Cells(10, componentlist(1, i)), Cells(21, componentlist(1, i)))

Next

我对 VBA 的经验有限,所以你们中的任何人都知道如何解决这个问题吗? 提前致谢!

【问题讨论】:

    标签: arrays excel vba for-loop


    【解决方案1】:

    Array() 创建一个下限为零的一维数组(除非您在模块顶部使用Option Base 1)。

    所以你应该从 0 循环到 ubound(componentlist)-1 并且你只需要使用 componentlist(i) 因为你的数组只有一维。

    【讨论】:

      【解决方案2】:

      您首先应该调查的是 LBOUND(componentlist) 是 1 还是 0,并在必要时修复 for 循环。

      接下来要修复的是 componentlist 的维度。它应该是单维的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        • 1970-01-01
        • 2016-04-21
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        相关资源
        最近更新 更多