簡體   English   中英

將VBA陣列打印到Excel單元格中

[英]Print VBA Array in to Excel Cells

我正在嘗試將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

它的application.transpose而不是工作表函數

  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

如果調用在另一個子組件中創建的數組,則會出現錯誤。 當您單步執行代碼時,可以在本地窗口中看到這個原因。 當你運行創建數組的sub時,它將以locals顯示,當sub結束時它將消失,這意味着它不再存儲在內存中。 要從另一個子引用變量或數組,您必須傳遞它。

傳遞數組或變量可以通過不同的方式完成,這里有一些鏈接Here And Here

你的PrecipRefET總是一樣的,這是RefET嗎?

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

一旦這樣做,我發現你沒有ReDimRunoffPercolation變量。 您需要將以下內容添加到WaterBalanceRead子中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM