VBA:无法在循环中为数组赋值

时间:2018-01-01 18:19:40

标签: arrays vba for-loop valueerror

我正在模拟数学生物学的蝉和捕食者的种群,我有一个问题是为一个叫做捕食者的二维数组赋值。它总是在单元格中响应#value错误。

对不起,我发送了一些更长的代码,但我不确定是什么导致了这个问题(我觉得它确实存在于"更新"部分但是有对其余代码的引用)。我已经尝试删除" Scalar产品的代码用于捕食者"和#34;更新新生掠食者"然后其余代码至少用于从cicada数组中获取值(请求CicSurvP = cicada(1,0)

我很感激任何帮助,因为捕食者的代码看起来类似于蝉的工作代码,我不知道可能出现什么问题。

'Distributions
Function OneX(k As Integer, i As Integer) As Double
    OneX = 1
End Function

Function Z_oneX(k As Integer, i As Integer) As Double
If i = 0 Then
    Z_oneX = 0
Else
    Z_oneX = 1
End If
End Function

'body
Function CicSurvP(c_length As Integer, p_length As Integer, c_surv As Double, p_surv As Double, c_danger As Double, p_meal As Double, c_baby As Double, p_baby As Double, c_max As Double, p_max As Double, c_init As Double, p_init As Double, length As Integer, ext As Double) As Double

'Declare variables
c_length = c_length - 1
p_length = p_length - 1
Dim cicada() As Double
Dim predator() As Double
ReDim cicada(length, c_length)
ReDim predator(length, p_length)
Dim c_temp As Double
Dim p_temp As Double
Dim p_t As Double
Dim c_t As Double
Dim i As Integer
Dim n As Integer

'Initiation
For i = 0 To c_length
    cicada(0, i) = c_init '*dist(i) multiply by the chosen distribution
Next
For i = 0 To p_length
    predator(0, i) = p_init '*dist(i) multiply by the chosen distribution
Next

'Update
For n = 0 To length - 1
    'Update cicada
    For i = 0 To c_length - 1
        cicada(n + 1, i + 1) = cicada(n, i) * c_surv
    Next
    'Update predator
    For i = 0 To p_length - 1
        If p_surv + p_meal * cicada(n, c_length) < 1 Then
            predator(n + 1, i + 1) = predator(n, i) * (p_surv + p_meal * cicada(n, c_length))
        Else
            predator(n + 1, i + 1) = predator(n, i)
        End If
    Next
    'Scalar product for cicada
    c_t = 0
    For i = 0 To p_length
        c_t = c_t + OneX(p_length, i) * predator(n, i)
    Next
    'Scalar product for predator
    p_t = 0
    For i = 0 To p_length
        p_t = p_t + Z_oneX(p_length, i) * predator(n, i)
    Next
    'Update newborn cicadas
    c_temp = c_surv * (c_baby - c_danger * c_t / cicada(n, c_length)) * cicada(n, c_length)
    If c_temp <= 0 Then
        cicada(n + 1, 0) = 0
    ElseIf c_temp <= c_max Then
        cicada(n + 1, 0) = c_temp
    Else
        cicada(n + 1, 0) = c_max
    End If
    'Update newborn predators
    p_temp = (p_surv + p_meal * cicada(n, c_length)) * p_baby * p_t
    If p_temp <= p_max Then
        predator(n + 1, 0) = p_temp
    Else
        predator(n + 1, 0) = p_max
    End If
Next
CicSurvP = predator(1,0)
End Function

0 个答案:

没有答案