简体   繁体   English

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

[英]Paste Array to Range in Excel VBA

I am trying to build an array containing ranges using a loop so I can paste it all together to earn some time.我正在尝试使用循环构建一个包含范围的数组,以便我可以将它们全部粘贴在一起以赢得一些时间。 The loop pastes stock name from column L to another sheet.该循环将 L 列中的股票名称粘贴到另一张纸上。 Then, dynamic values generate in range (CA59:CQ59).然后,动态值在范围内生成 (CA59:CQ59)。 I tried transpose function just in case, double loop for manual 2d array,and simpler ranges without luck.为了以防万一,我尝试了转置函数,手动二维数组的双循环,以及没有运气的更简单的范围。 My best shot was something like我最好的镜头是这样的

Sheets("Stocks | Sort").Range("O2:O" & UBound(pool) + 1) = WorksheetFunction.Transpose(pool)   

returned one column.返回一列。 Apologize for my lack of knowledge.为我的知识缺乏道歉。 Any ideas would be highly appreciated.任何想法将不胜感激。 Here is my code :这是我的代码:

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

It returns blanks.它返回空白。 Thank you for your time in advance.提前感谢您的时间。

Made a few changes in your code with explanation.对您的代码进行了一些更改并附有说明。 Array populated from Worksheet column or row or table range values is a two dimensional array.从工作表列或行或表范围值填充的数组是二维数组。

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