我对您提供的代码做了一些工作(如下面的注释所示),主要需要仔细调试程序的逻辑。您仍然会收到编译器错误,因为您的代码中没有分配两个数组,而且我没有足够的信息来正确执行此操作。
VBA 中用于驯服顽固代码的最佳资源是内置调试器。有了它,就可以逐行逐行查看每个变量在每一步中的变化情况。
如果你对调试器不熟悉,网上有很多很好的解释,比如 Chip Pearson对基础的解释。
可以使循环和索引更易于处理的一项更改是将“第 13 个月”值放入与数组分开的变量中,这将是直接的 12 个月数据集合。
这将是一种减少否则需要的令人困惑的簿记的方法(“程序中此时的索引应该是 j,还是 j - 1,还是 j + 1?”)。我不知道这种方法是否真的适合您的数据和计算。
Option Explicit ' Require declaration of all variables
Private Const NumMonth As Long = 12 ' Make these variable available to all subroutines
Private month As Variant ' and functions in the module. Needed because they
Private WCinit As Variant ' would otherwise be out of scope in the Test()
Private WC As Variant ' subroutine.
Private Precip As Variant ' The arrays need to be declared as type Variant,
Private RefET As Variant ' so we can make the assignment
Private Percolation As Variant
Private Runoff As Variant
Sub Read()
Dim firstMoDataRow As Long
Dim lastMoDataRow As Long
firstMoDataRow = 5
lastMoDataRow = 16
' if you want to avoid using the transpose function in the following
' array assignments, you will need to reference the arrays as
' two-dimensional, e.g., WC(i,1) or WC(3,1), etc., with the
' second index always 1 (that's what many often do).
month = WorksheetFunction.Transpose(Range(Cells(firstMoDataRow, 1), Cells(lastMoDataRow, 1)).Value) ' Direct assignment of values
WCinit = WorksheetFunction.Transpose(Range(Cells(firstMoDataRow, 10), Cells(lastMoDataRow, 10)).Value) ' in the worksheet ranges
WC = WorksheetFunction.Transpose(Range(Cells(firstMoDataRow - 1, 11), Cells(lastMoDataRow, 11)).Value) ' to the arrays.
Precip = WorksheetFunction.Transpose(Range(Cells(firstMoDataRow, 2), Cells(lastMoDataRow, 2)).Value)
RefET = WorksheetFunction.Transpose(Range(Cells(firstMoDataRow, 3), Cells(lastMoDataRow, 3)).Value)
' ?! Percolation and runoff are not assigned in your code, so I don't know
' the correct row and column references in the worksheet.
End Sub
Sub Test()
Dim fc As Double
Dim pwp As Double
Dim dz As Double
Dim i as Long, j as Long
fc = 0.3
pwp = 0.1
dz = 0.5 'm
i = 1
j = 2
Do While i <= NumMonth And j <= NumMonth + 1 ' I am assuming here that you will sort out
' the correct initializing and incrementing
' of the loop indexes, which I have not
' puzzled out
If WC(j - 1) + WCinit(i) > pwp And fc - (WC(j - 1) + WCinit(i)) + RefET(i) < Precip(i) Then
Runoff(i) = (Precip(i) - (fc - (WC(j - 1) + WCinit(i)) + RefET(i))) * 0.5
Percolation(i) = (Precip(i) - (fc - (WC(j - 1) + WCinit(i)) + RefET(i))) * 0.5
WC(j) = fc
ElseIf WC(j - 1) + WCinit(i) > pwp And fc - (WC(j - 1) + WCinit(i)) + RefET(i) < Precip(i) Then
' You are getting a "Subscript out of range" error here because Runoff() and
' Percolation<> did not get assigned in the Read sub
Runoff(i) = 0
Percolation(i) = 0
WC(j) = WC(j - 1) + WCinit(i) + Precip(i) - RefET(i)
Else
WC(j) = pwp
End If
j = j + 1
i = i + 1
Loop
End Sub