VBA定义数组的范围

时间:2016-04-05 18:21:00

标签: arrays vba excel-vba range excel

所以我有一个包含1000行和10列的2d数组。我想为10列中的每一列创建10个范围,然后将它们用作系列来制作图表。我的问题是,如何在不使用整个数组的情况下从数组中定义范围,只需要一列?

Sub ChartLord()

    Dim rows As Long
    Dim columns As Integer
    Dim mychart As Chart
    Dim data As Range
    Dim dataset() As Double

    rows = ShData.Cells(ShData.rows.Count, 1).End(xlUp).Row
    columns = ShData.Cells(1, ShData.columns.Count).End(xlToLeft).Column

    'set array range (includes column titles and xAxix column)
    dataset = ShData.Range(ShData.Cells(1, 1), ShData.Cells(rows, columns))



    For Z = 0 To 10

        Set data = ?
        Set mychart = shtCharts.Shapes.AddChart2(200, xlColumnClustered, 50 + 300 * Z, 50, 300, 200, 5).Chart


    Next Z



End Sub

1 个答案:

答案 0 :(得分:4)

以下内容将您的范围值收集到2D范围,然后将第二列切成新的2D​​数组。后者只是1到1'列'宽。

Dim rws As Long, cols As Long, d As Long
Dim dataset() As Variant, subdataset() As Variant
Dim ShData As Worksheet

Set ShData = Worksheets("Sheet4")

rws = ShData.Cells(ShData.rows.Count, 1).End(xlUp).Row
cols = ShData.Cells(1, ShData.columns.Count).End(xlToLeft).Column

'set array range (includes column titles and xAxix column)
dataset = ShData.Range(ShData.Cells(1, 1), ShData.Cells(rws, cols))

subdataset = Application.Index(dataset, 0, 2) '<~~second column
For d = LBound(subdataset, 1) To UBound(subdataset, 1)
    Debug.Print subdataset(d, 1)
Next d

ShData.Cells(1, "Z").Resize(UBound(subdataset, 1), UBound(subdataset, 2)) = subdataset

最后一个操作将剥离列的值放回到从Z1开始的工作表中。