excel 将数组写入表

btxsgosb  于 2023-04-13  发布在  其他
关注(0)|答案(3)|浏览(145)

我正在尝试编写一个函数,将二维数组中的数据输出到空表中。

Function WriteArrayToTable(InputArray() As Variant, TableName As String, SheetName As String)
    Dim MyTable As ListObject: Set MyTable = Worksheets(SheetName).ListObjects(TableName)
    MyTable.DataBodyRange.Value = InputArray
End Function

然而,我得到了一个对象变量,它没有在第二行设置。我已经尝试了包括和排除Set和DataBodyRange.Value的各种排列。当我设置我的手表时,它可以找到MyTable,InputArray是合适的大小,但是MyTable.DataBodyRange是Nothing。

eoigrqb6

eoigrqb61#

试试这个代码:

Function WriteArrayToTable(InputArray() As Variant, TableName As String, SheetName As String)
    Dim MyTable As ListObject: Set MyTable = Worksheets(SheetName).ListObjects(TableName)
    Dim target As Range 'helper var for output point
    With MyTable
        If .DataBodyRange Is Nothing Then
            ' table is empty: output point - under the header
            Set target = .HeaderRowRange.Cells(1, 1)
        Else
            ' table not is empty: output point - at the end of the table
            Set target = .DataBodyRange.Cells(.DataBodyRange.Rows.Count, 1)
        End If
        target.Offset(1).Resize(UBound(InputArray, 1), UBound(InputArray, 2)).Value = InputArray
    End With
End Function
9rygscc1

9rygscc12#

正如您所观察到的,当Table为空时,DataBodyRange就是Nothing
在这种情况下,请使用InsertRowRange

If MyTable.DataBodyRange Is Nothing Then
    MyTable.InsertRowRange = ...
Else
    `...
End If
sxissh06

sxissh063#

将数组写入表

  • 假设数组的列数与表的列数相同。
Option Explicit

Sub WriteArrayToTable( _
        ByVal InputArray As Variant, _
        ByVal TableName As String, _
        ByVal SheetName As String)
    Dim MyTable As ListObject
    Set MyTable = ThisWorkbook.Worksheets(SheetName).ListObjects(TableName)
    Dim srCount As Long: srCount = UBound(InputArray, 1)
    MyTable.HeaderRowRange.Offset(1).Resize(srCount).Value = InputArray
    With MyTable.DataBodyRange
        Dim drCount As Long: drCount = .Rows.Count
        If drCount > srCount Then
            .Resize(drCount - srCount).Offset(srCount).Delete
        End If
    End With
End Sub

相关问题