[英]Paste Array to Range in Excel VBA
我正在嘗試使用循環構建一個包含范圍的數組,以便我可以將它們全部粘貼在一起以贏得一些時間。 該循環將 L 列中的股票名稱粘貼到另一張紙上。 然后,動態值在范圍內生成 (CA59:CQ59)。 為了以防萬一,我嘗試了轉置函數,手動二維數組的雙循環,以及沒有運氣的更簡單的范圍。 我最好的鏡頭是這樣的
Sheets("Stocks | Sort").Range("O2:O" & UBound(pool) + 1) = WorksheetFunction.Transpose(pool)
返回一列。 為我的知識缺乏道歉。 任何想法將不勝感激。 這是我的代碼:
Sub ForecastAll()
Dim line As Range
Dim pool() As Variant
Dim i As Long
For i = 2 To 133
Sheets("Stocks | Sort").Range("L" & i).Copy (Sheets("Stocks | Synopsis").Range("E3"))
ReDim Preserve pool(i)
pool(i) = Sheets("Stocks | Synopsis").Range("CA59:CQ59").Value
Next i
Sheets("Stocks | Sort").Range("O2:AE133").ClearContents
Sheets("Stocks | Sort").Range("O2:AE133").Value = pool
End Sub
它返回空白。 提前感謝您的時間。
對您的代碼進行了一些更改並附有說明。 從工作表列或行或表范圍值填充的數組是二維數組。
Sub ForecastAll()
Dim pool() As Variant
Dim i As Long
'clearing target range first to fill it with the loop below
Sheets("Stocks | Sort").Range("O2:AE133").ClearContents
For i = 2 To 133
Sheets("Stocks | Sort").Range("L" & i).Copy (Sheets("Stocks | Synopsis").Range("E3"))
ReDim Preserve pool(i)
'pool(i) = Sheets("Stocks | Synopsis").Range("CA59:CQ59").Value
'pool is one dimensional array where in at each iteration you are entering _
'a two dimensional array. Which can be ensured with --
'Debug.Print UBound(pool), Join(Application.Index(pool(i), 1, 0), ",")
'instead of using an array you can directly assign values of one range to another like --
Sheets("Stocks | Sort").Range("O2:AE" & i).Value = Sheets("Stocks | Synopsis").Range("CA59:CQ59").Value
'This method should also work fast as it is not selecting ranges and copying-pasting values _
'If you still want to use array, it should be a 2D array and it can not be populated directly _
'from range and it will need a loop to populate that array
Next i
'Sheets("Stocks | Sort").Range("O2:AE133").ClearContents
'Sheets("Stocks | Sort").Range("O2:AE133").Value = pool
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.