简体   繁体   English

将未知大小的数组粘贴到工作簿(VBA)上的某个位置

[英]Paste an array of unknown size to a location on a workbook (VBA)

I have a function that creates dynamic arrays based on the content of different sheets- each array is of a different size. 我有一个函数可以根据不同工作表的内容创建动态数组-每个数组的大小都不同。 I would like to paste the contents of each array into the worksheet on which the function was called. 我想将每个数组的内容粘贴到调用该函数的工作表中。 Given that each array is of different size, it seems I cannot use the transpose function. 鉴于每个数组的大小不同,看来我无法使用转置函数。 Any suggestions? 有什么建议么?

Here is the function that creates the arrays: 这是创建数组的函数:

Function FindConstituents(ByRef ys As Worksheet) As String()
Dim a() As String
Dim size As Integer
Dim i As Integer
Dim j As Integer

size = 0
Dim row As Integer
row = 2
ReDim Preserve a(size)
While ys.Cells(row, 4) <> ""
    If IsInTable(ys.Cells(row, 4), ys, 2) Then
    ReDim Preserve a(size)
    a(size) = ys.Cells(row, 4)
    size = size + 1
    End If
    row = row + 1
Wend
size = size + 1

<<Code to paste contents of a() onto a place in the worksheet>>

FindConstituents = a
End Function

You would use Resize, something like to get the results in one column: 您将使用Resize,类似于将结果放在一栏中:

ys.Range("G1").Resize(Ubound(a)+1).Value = Application.Transpose(a)

If you do not want to use Transpose then you will need to iterate through a. 如果您不想使用转置,则需要遍历a。

Dim i as long
For i = Lbound(a) to Ubound(a)
    ys.Range("G1").Offset(i).Value = a(i)
Next i

Edit just realized you probably are calling this from the worksheet. 编辑只是意识到您可能正在工作表中调用它。 This will need to be called from a sub that does the pasting back to the sheet a function called by a worksheet cannot affect the values of other cells. 这需要从将其粘贴回工作表的子项中调用,该工作表调用的函数不能影响其他单元格的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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