使用 VBA 将数组粘贴到 MS Excel 中的列范围

问题描述 投票:0回答:1

问题:开发一个子过程,将一组数据粘贴到 MS Excel 工作表中的一系列单元格中(不循环)。

注意: 函数 build_date_array 和 populate_date_array 协同工作以在数组中创建和存储数据。子过程paste_array 在尝试将数据粘贴到工作表“test”之前调用这些函数。在下面编码的示例中,子过程按原样错误地粘贴了数组的第一个元素。请参阅随附的两张图片。


build timeline data storage array
Function build_date_array(length As Integer) As Variant

' declare array variable
Dim eNumStorage() As String ' initial storage array to take values

' dimension the array
ReDim eNumStorage(1 To length)

' set empty array to variable to pass back to module
build_date_array = eNumStorage

End Function
' Populate a date array
Function populate_date_array(dimed_array As Variant, start As Variant) As Variant

Dim i As Long

' iterate through dimension empty array to populate it with data
For i = LBound(dimed_array) To UBound(dimed_array)
   
    If i = LBound(dimed_array) Then
        ' first element of array needs to be the desired start
        dimed_array(i) = Format(WorksheetFunction.EDate(start, 0), "MM/DD/YYYY")
    Else
        ' kick in function for 2nd element to end of array
        dimed_array(i) = Format(WorksheetFunction.EDate(start, i - 1), "MM/DD/YYYY") ' https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.edate
    End If
   
Next i

populate_date_array = dimed_array

End Function
Sub paste_array()

Dim wb As Workbook, sh As Worksheet, date_array As Variant, horizon As Integer

Set wb = ActiveWorkbook '  instance of workbook
Set sh = wb.Sheets("test") ' instance of sheet

horizon = 5 ' time increment in months

date_array = build_date_array(horizon) ' build empty array

date_array = populate_date_array(date_array, "10/01/2024")  ' populate array

LastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row + 1 ' get last row

'sh.Range("A2").Resize(UBound(date_array), 1).Value = date_array

sh.Range(sh.Cells(LastRow, 1), sh.Cells(UBound(date_array), 1)).Value = date_array

End Sub

代码和输出的分屏视图:

enter image description here

arrays excel vba
1个回答
0
投票

请尝试

sh.Cells(LastRow, 1).Resize(UBound(date_array), 1).Value = Application.Transpose(date_array)
© www.soinside.com 2019 - 2024. All rights reserved.