填充动态多维,多类型数组的Excel VBA

时间:2015-01-14 19:08:57

标签: arrays excel vba excel-vba

我正在尝试使用excel 2010 VBA来填充包含三个数组的数组。第一个是字符串类型数组,另外两个是整数类型数组。宏的相关部分如下。

Option Explicit
Option Base 1
Private Type T_small

    myStr() As String
    y() As Integer
    z() As Integer
End Type

Sub ColorByPoint()

On Error GoTo ErrHandler

Dim I As Integer, SCCount As Integer, PCCount As Integer, CLCount As Integer
Dim N As Integer, M As Integer, K As Integer, P As Integer
Dim x() As String, y() As Integer, z() As Integer
Dim pvtItM  As Variant
Dim xName As String, str As String
Dim xlRowField As Range
Dim PC As ChartObjects
Dim WS As Sheet3
Dim SC As SeriesCollection
Dim MyObj As Object
Dim PvTbl As Object
Dim CelVal As Integer
Dim rng As Variant, lbl As Variant, vlu As Variant
Dim ItemField1 As PivotItem, ItemField2 As PivotItem
Dim ValueField As PivotField
Dim dField As PivotCell
Dim oPi As PivotItem
Dim acolRng As Range
Dim arowRng As Range
Dim myStr() As String
Dim iData() As T_small
Dim xSSN() As String

Set WS = Application.ActiveWorkbook.ActiveSheet

Set MyObj = Worksheets("Pivot1").ChartObjects("MyChart").Chart
Set PvTbl = Worksheets("Pivot1").PivotTables("PivotTable1")
Set rng = PvTbl.PivotFields("SSN").PivotItems
Set lbl = PvTbl.DataFields
M = 1

SCCount = MyObj.SeriesCollection.Count          'Series count
PCCount = PvTbl.TableRange1.Rows.Count          'Rows Count
CLCount = PvTbl.TableRange1.Columns.Count    'Columns Count


Set acolRng = PvTbl.ColumnRange
Set arowRng = PvTbl.RowRange
Worksheets("Pivot1").Activate

 P = PCCount

    ReDim Preserve myStr(P)
    ReDim Preserve y(P)
    ReDim Preserve z(P)
    ReDim Preserve iData(P)
For N = 2 To PCCount
    ReDim Preserve iData((iData(2).myStr(2)), (iData(N).y(N)),(iData(N).z(N)))
Next N


For I = 2 To PvTbl.TableRange1.Rows.Count Step 1
    For K = 2 To PvTbl.TableRange1.Columns.Count Step 1
        M = K
        N = K

        iData(I).myStr(I) = PvTbl.Cells("myStr" & I, "K").Value
        iData(I).y(I) = PvTbl.Cells("I", "M").Value
        iData(I).z(I) = PvTbl.Cells("I", "N").Value
    Next K
Next I

问题在于行

ReDim Preserve iData((iData(2).myStr(2)), (iData(N).y(N)), (iData(N).z(N)))

继续给我一个“运行时错误9下标超出范围”错误。我已经尝试了所有我能想到的事情,包括使用“N”而不是“2”索引,添加和删除括号等。

导致运行时错误的原因是什么?

1 个答案:

答案 0 :(得分:0)

问题是您正在访问T_small属性的数组索引。你永远不会定义(或改变)iData(x).myStr的界限;相反,定义myStr的范围,iData数组的一部分。

换句话说,边界错误来自于尝试访问iData(x).myStr(x),因为iData(x).myStr没有定义边界。

这应该有效:

' Now that the iData bounds have been defined, update the property bounds.
ReDim Preserve iData(N).myStr(myStr(N))
ReDim Preserve iData(N).y(y(N))
ReDim Preserve iData(N).z(z(N))

请注意,我确实在确定您的代码尝试完成的内容时遇到了一些困难,因此上述内容仅解决了您遇到的具体错误。