VBA不会将数组传递给子对象

时间:2018-08-16 14:56:31

标签: arrays excel vba

我试图将3个值传递给第二个子控件,每3列的“通道”名称是一个具有不同名称的不同数据集。 “测试”是测试文件的名称,用于从该数据中提取通道并从中创建图形。

Sub PickTests()

Dim Channame() As String
Dim Amplitude() As String
Dim Integration() As String
Dim LvlCross() As String
Dim MaxAnal() As String
Dim Chans As Double
Dim x As Long
Dim TestList() As Double
Dim i As Long


Worksheets("Channel_List.csv").Activate

For i = 1 To (Cells(i + 2, 1).Value = 0)
    Channame(i) = Cells(i + 1, 1)
    Amplitude(i) = Cells(i + 1, 2)
    Integration(i) = Cells(i + 1, 3)
    LvlCross(i) = Cells(i + 1, 4)
    MaxAnal(i) = Cells(i + 1, 5)
    Chans = i + 1
Next i

Worksheets("HomeSheet").Activate
  ' Set numrows = number of rows of data.
    NumRows = Range("A14", Range("A14").End(xlDown)).Rows.Count
  ' Select cell a1.
    Range("A4").Select
  ' Establish "For" loop to loop "numrows" number of times.
    For x = 1 To NumRows
     TestList(x) = Cells(x, 1).Value
     ActiveCell.Offset(1, 0).Select

Next x

    For i = 1 To Chans
    If Amplitude(i) = y Then
    AmplitudeDistribution(Channame(i), TestList)
    End If

Next i






End Sub


Sub AmplitudeDistribution(Channame As String, Test() As Long)

Dim i, j, y, x As Long
Dim wsname As String
wsname = (Channame & "_Amp_Dist")
x = UBound(Test, 1) - LBound(Test, 1) + 1

Worksheets.Add.Name = wsname
Charts.Add
ActiveChart.ChartType = xlLineStacked
ActiveChart.Location Where:=wsname, Name:=Channame


For i = 1 To x
    ActiveChart.SeriesCollection.NewSeries
    Sheets(Test(i) & "_out_Amp_Dist.csv").Activate
    With ActiveSheet
        Set FindColumn = .Range("1:1").Find(What:=Channame, LookIn:=xlValues)
    End With
    y = FindColumn.Row

    For j = 1 To (Cells(y, j + 1).Value = 0)
        NumRow(i) = j
    Next j

    ActiveChart.SeriesCollection(i).Values = ActiveSheet.Range(Cells(y, 1), Cells(y + 1, j))
    ActiveChart.SeriesCollection(i).Name = Channame
Next i



End Sub

我在尝试将TestList传递给第二个子元素时遇到错误类型不匹配错误。我该如何解决?

编辑:谢谢大家的帮助,我来自c ++背景,所以没有意识到VBA中的动态数组是多么愚蠢!现在一切正常! (不是全部,但它会将所有内容传递给第二个子,不,我只是在与图表搏斗...。)

1 个答案:

答案 0 :(得分:1)

DisplayName saw it quick

数组在这里声明:

Dim TestList() As Double

并传递到这里:

Sub AmplitudeDistribution(Channame As String, Test() As Long)

您收到类型不匹配错误,因为类型..不匹配。将参数更改为Double的数组,或将TestList()声明为Long的数组。

或者,只需将数组作为Variant传递:

Sub AmplitudeDistribution(Channame As String, Tests As Variant)

无论使用哪种类型,我都会使用复数名称,并且由于Variant可以按字面意义包装任何内容,因此您可能需要添加调试安全网:

    Debug.Assert IsArray(Tests) ' will break here if Tests isn't an array

您在声明数组,但是这些数组是动态调整大小的,除非删除该代码以进行发布,否则数组将永远不会初始化,这意味着一旦将数组放入该参数,下一个错误将是“索引”尝试写TestList(x)或阅读Test(i)时越界。

使用ReDim语句调整数组大小:

ReDim TestList(1 To NumRows)

您需要对所有数组执行此操作。


这很可疑:

For i = 1 To (Cells(i + 2, 1).Value = 0)

表达式(Cells(i + 2, 1).Value = 0)是一个Boolean表达式,因此您正在将i1循环到0(假)或-1 (正确),这意味着您永远不会进入循环。