将VBA数组打印到Excel单元格中

我正在尝试将一个VBA创build的数组打印到Excel电子表格的单元格中。 渗stream和径stream值不断得到“下标超出范围”的错误我是否正确创build软pipearrays? 我已经将计算和打印子function合并为一个。

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 

你的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 

一旦这样做,我发现你没有ReDimRunoffPercolationvariables。 您需要将以下内容添加到WaterBalanceRead子项中。

 ReDim Runoff(1 To NumMonth + 1) ReDim Percolation(1 To NumMonth + 1) 

它的application.transpose而不是工作表function

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

这是一个testing子

 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 

如果您调用在另一个子文件中创build的数组,将会出错。 这个原因可以通过你的代码在本地窗口看到。 当你运行创build你的数组的子将会在本地显示,当子结束它将消失,这意味着它不再存储在内存中。 要从另一个子引用一个variables或数组,你必须通过它。

传递数组或variables可以以不同的方式完成,这里有几个链接在这里 和这里