【发布时间】:2019-09-26 09:18:11
【问题描述】:
我编写了一个函数来将二维数组的内容写入现有表。不会从表中删除任何内容。新行必须添加到底部。列数取决于数组第二维的大小,我假设表有足够的列。
我的问题是:如何在没有以下情况的情况下引用表中的范围: a)将带有表格的表格作为活动表格,并且 b) 无需参考工作表(就像现在在代码中一样;见下文)?
请参阅下面我尝试过的代码。
Function PasteArrayToTable(tblDestinationTable As ListObject, arrSourceArray() As Variant)
'Note: works for arrays starting with index = 1 (option base 1)!
Dim lngNewRows As Long
Dim lngHeaderRowPosition As Long
Dim intHeaderColumnPosition As Long
Dim lngFirstRow As Long
Dim lngLastRow As Long
Dim intFirstColumn As Integer
Dim intLastColumn As Integer
Dim lngNrOfRecordsAtStart As Long
'Number of rows to be added
lngNewRows = UBound(arrSourceArray, 1)
'If the array contains rows, then write them to the destination table
If lngNewRows > 1 Then
'Get header position of destination table
lngHeaderRowPosition = tblDestinationTable.HeaderRowRange.Row
intHeaderColumnPosition = tblDestinationTable.HeaderRowRange.Column
'Get number of records in table before pasting array, in order to remove afterwards an empty row if the table has 0 rows
lngNrOfRecordsAtStart = tblDestinationTable.ListRows.Count
'Add rows to table
tblDestinationTable.Resize tblDestinationTable.Range.Resize(tblDestinationTable.Range.Rows.Count + lngNewRows)
'Determine positions where to write array to
lngFirstRow = lngHeaderRowPosition + tblDestinationTable.ListRows.Count + 1 - lngNewRows
lngLastRow = lngHeaderRowPosition + tblDestinationTable.ListRows.Count
intFirstColumn = intHeaderColumnPosition
intLastColumn = intFirstColumn - 1 + UBound(arrSourceArray, 2)
'Write array to determined positions. Note: there's no check whether the table has the required number of columns, nor
'whether the number of lines fit on the page
Dim wks As Worksheet
Set wks = Worksheets("Blad1")
With wks
.Range(.Cells(lngFirstRow, intFirstColumn), .Cells(lngLastRow, intLastColumn)).Value = arrSourceArray
End With
'Remove empty row if present
If lngNrOfRecordsAtStart = 0 Then
tblDestinationTable.ListRows(1).Delete
End If
End If
End Function
那么如何引用表格中的“单元格”呢?
【问题讨论】:
-
ListObject.Parent返回对表格所在工作表的引用。 -
您也可以考虑使用表的
DataBodyRange,而不是Range。 -
@BigBen:非常感谢,我解决了!
-
@BigBen:是的,带有 'tblDestinationTable.DataBodyRange' 的东西会更好,但是如何引用列子集与行子集的组合?
-
@BigBen:是的,我用 DataBodyRange.Cells 解决了这个问题,现在必须调整一些代码以从正确的行开始。谢谢!
标签: arrays excel vba listobject