在VBA中键入不匹配

时间:2014-04-05 16:06:52

标签: excel-vba type-mismatch vba excel

我正在尝试运行此代码:

Function Main()
 Dim arr() As Variant
 arrValues = Range("D2:D106")
 arr = arrValues

End Function

Function stAvg()
Dim CustList() As Variant

Dim forecast() As Double

CustList = Main()

'loop through array to find average
For X = 1 To 52
        forecastNumber = WorksheetFunction.Average(CustList(X, 1), CustList(X + 1, 1), CustList(X + 2, 1), CustList(X + 3, 1))
        forecast(X) = forecastNumber
    Next X

    For X = 1 To 3
        MsgBox forecast(X, 1)
    Next X


End Function

在我使用调试器后,我收到一条错误消息,告诉我在Main函数的末尾有一个类型不匹配。但是错误信息有点模糊,我不知道问题是什么。帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

您不需要Main成为Function,至少在此处显示时,因为它不会返回任何内容。所以我把它变成了Sub

对于您的实际问题,只需将arr设置为Range即可。正如我在回答您的另一个问题的评论中所述,请使用arr,而不是arr()

Sub Main()
Dim arr As Variant

arr = Range("D2:D106")
End Sub

编辑:将其用作功能:

Function Main() as Variant
Dim arr As Variant

arr = Range("D2:D106")
Main = arr
End Function

称之为:

Dim CustList As Variant
...
CustList = Main()

正如样式注释Main通常指定程序中的主子例程一样,所以我将函数称为GetRangeValues之类的函数。

答案 1 :(得分:1)

问题是你永远不会从函数中返回任何内容。您分配了一些局部变量,这没有意义。你必须实际返回一个值,在VB6(A)中你可以通过为函数名赋值:

Function Main()
  Main = Range("D2:D106").Value
End Function

然后你可以使用它:

Dim CustList() As Variant

CustList = Main()

答案 2 :(得分:0)

要使用Worksheet函数,您应该使用RAnge对象而不是数组。 为此,将main更改为返回范围

Function Main()
    Set Main = Range("D2:D106")
End Function

更改平均值以引用范围

中的单元格位置
Function stAvg()
    Dim CustList
    Dim forecast(52)

    Set CustList = Main()

    'loop through array to find average
    For X = 1 To 52
        forecastNumber = WorksheetFunction.Average(CustList.Cells(X, 1), CustList.Cells(X + 1, 1),         CustList.Cells(X + 2, 1), CustList.Cells(X + 3, 1))
    forecast(X) = forecastNumber
    Next X

    For X = 1 To 3
        MsgBox forecast(X, 1)
    Next X
End Function