繁体   English   中英

将数组粘贴到 Excel VBA 中的范围

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM