键入Mismatch VBA数组

时间:2014-11-12 01:39:19

标签: arrays vba access-vba

我尝试运行代码时遇到类型不匹配错误。我正在尝试将数字存储在一个数组中,然后计算它们的总和。

Sub Exercise()

    Dim Sum As Integer

    Dim A(1 to 5) As Integer
    A(1) = 35
    A(2) = 71
    A(3) = 42
    A(4) = 53
    A(5) = 109

    Sum = 0
    Sum = (Sum + A)

    For A = 1 To 5
    Next Sum

    MsgBox Sum

End Sub

2 个答案:

答案 0 :(得分:4)

我相信你的意思是这样做:

Sub Exercise()
    Dim Sum As Integer
    Dim i As Integer
    Dim A(1 To 5) As Integer

    A(1) = 35
    A(2) = 71
    A(3) = 42
    A(4) = 53
    A(5) = 109

    Sum = 0
    For i = 1 To 5
        Sum = (Sum + A(i))
    Next i

    MsgBox Sum
End Sub

注意差异。您在循环之前设置Sum = 0,然后使用迭代变量i通过使用A调用它们来遍历A(i)的值。这会将每个A(i)添加到Sum定义的运行总计中。

答案 1 :(得分:1)

你不能使用A作为循环计数器,它就是你的数组。

您可能打算这样做:

Dim i As Integer
For i = 1 To 5
    Sum = Sum + A(i)
Next

请注意,Sum已初始化为0,因此这一行是多余的:

Sum = 0

尝试分配Sum = (Sum + A)的行只能被移除,您无法添加带有数组的Integer