1

我正在尝试将 VBA 创建的数组打印到 excel 电子表格的单元格中。渗透和径流值不断出现“下标超出范围”错误我是否正确创建软管阵列?我已将计算和打印子功能合并为一个。

 NumMonth = 12
 Dim col As Long
 Dim rw As Long
 rw = 4
 col = 13

 Range(Cells(rw, col), Cells(rw + NumMonth - 1, col)).Value = _
    Application.Transpose(WC)

Range(Cells(rw, col + 1), Cells(rw + NumMonth - 1, col + 1)).Value = _
    Application.Transpose(Runoff)

   Range(Cells(rw, col + 2), Cells(rw + NumMonth - 1, col + 2)).Value = _
     Application.Transpose(Percolation)
   End Sub
4

2 回答 2

2

它的 application.transpose 而不是 worksheetfunction

  Range(Cells(rw, col), Cells(rw + NumMonth - 1, col)).Value = _
      application.Transpose(WC)

这是一个测试子

Sub test()
Dim myarray As Variant

'this is a 1 row 5 column Array
myarray = Array(1, 2, 3, 4, 5)

'This will fail because the source and destination are different shapes
Range("A1:A5").Value = myarray


'If you want to enter that array into a 1 column 5 row range like A1:A5

Range("A1:A5").Value = Application.Transpose(myarray)
End Sub

如果你调用你在另一个子中创建的数组,你会得到一个错误。当您单步执行代码时,可以在本地窗口中看到其原因。当您运行创建数组的子程序时,它将显示在本地,当子程序结束时它将消失,这意味着它不再存储在内存中。要从另一个子引用变量或数组,您必须传递它。

传递数组或变量可以用不同的方式完成这里有几个链接 Here And Here

于 2013-02-22T20:18:10.360 回答
1

你的PrecipRefET永远是平等的,这难道就是吗?

Precip(i) = Cells(4 + i, 2).Value
RefET(i)  = Cells(4 + i, 2).Value

此外,当您设置RunoffPercolation数组时,如果您的 if 语句不满足(如下),它们不会被设置为任何内容,我可以使用提供的数据来满足它:

If (fc - WC(j - 1) + RefET(i) * dz < Precip(i) * dz) then

我会添加一些东西以确保它们总是有价值:

If (fc - WC(j - 1) + RefET(i) * dz < Precip(i) * dz) Then
    Runoff(i) = (Precip(i) - (fc - WC(j - 1) + RefET(i)) * dz) * 0.5
    Percolation(i) = (Precip(i) - (fc - WC(i - 1) + RefET(i)) * dz) * 0.5
    WC(j) = fc
Else
    Runoff(i) = 0
    Percolation(i) = 0
    WC(j) = WC(j - 1) + Precip(i) - RefET(i) / dz
End If

这样做后,我发现您没有ReDim使用RunoffandPercolation变量。 您需要将以下内容添加到您的WaterBalanceRead子目录中。

ReDim Runoff(1 To NumMonth + 1)
ReDim Percolation(1 To NumMonth + 1)
于 2013-02-23T00:01:37.687 回答