简体   繁体   English

如何在Excel VBA中将数组输出到表?

[英]How do I output an array to a table in Excel VBA?

I have a table named foobar that has Range(Cells(2, 1), Cells(11, 2)) (use Range("foobar[#All]") to include the header row). 我有一个名为foobar的表,该表具有Range(Cells(2, 1), Cells(11, 2)) Range("foobar[#All]") Range(Cells(2, 1), Cells(11, 2)) (使用Range("foobar[#All]")包括标题行)。 And there are other tables starting from row 13. So there is a blank line between (ie, row 12). 并且从第13行开始还有其他表。因此,在它们之间(即第12行)有一个空白行。 The table name is used by my collegues in several other macros. 表名称由我的同事在其他几个宏中使用。 Now, I'd like to copy an array, say, Redim array1(1 To n, 1 To 2) to table foobar . 现在,我想复制一个数组,例如Redim array1(1 To n, 1 To 2)到表foobar As you see, n is a variable, and I have to make sure after I paste the array starting from Cells(2, 1) , it won't overwrite the tables below and there is still one blank line below table foobar to separate it from other tables. 如您所见,n是一个变量,在粘贴从Cells(2, 1)开始的数组后,我必须确保它不会覆盖下面的表,并且在表foobar下方仍然有一个空行来分隔它从其他表。 And the name foobar should also be kept. 并且名称foobar也应保留。


How do I auto adjust/add/reduce the rows to match my array array1 and not to destroy table foobar and other tables below it? 如何自动调整/添加/减少行以匹配数组array1而不破坏表foobar及其下面的其他表?

Fortunately you don't have data and tables on the same rows, so the task is easier. 幸运的是,您没有在同一行上包含数据和表,因此该任务更加容易。 This code snippet changes the content of the table foobar while not affecting the table(s) below it. 此代码段更改了表foobar的内容,同时不影响其下面的表。

Sub ChangeTableToArray(tbl As ListObject, ar)
  Dim newRows As Long: newRows = 1+ UBound(ar,1) - LBound(ar,1)
  If Not tbl.DataBodyRange Is Nothing Then tbl.DataBodyRange.EntireRow.Delete
  If newRows > 1 Then tbl.HeaderRowRange.Resize(newRows - 1).Offset(2).EntireRow.Insert
  tbl.HeaderRowRange.Resize(newRows, 1+UBound(ar,2)-LBound(ar,2)).Offset(1).Value = ar
End Sub

Sub Testing()
  Dim n As Long: n = 15
  ReDim ar(1 To n, 1 To 2)
  For n = 1 To n
    ar(n, 1) = n
    ar(n, 2) = n * n
  Next
  ChangeTableToArray Sheet2.ListObjects("foobar"), ar
End Sub

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

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