如何更改我正在进行复制的表格名称?
我已经有了一张表,我可以成功地用下面的程序进行复制
Private Sub prev_comments_button_Click()
Dim tbl As ListObject: Set tbl = Sheets("Summary").ListObjects("t_sum")
Dim lr As Integer
lr = get_tbl_size + 2 ' gets the table size of the current table _
and we move by two rows, to indent the copied table
tbl.Range.Copy Destination:=Sheets("Summary").Range("B" & lr)
End Sub
问题是,有时我的表索引会出现故障,为复制的表分配一个名称,例如t_sum3而不是t_sum2,这意味着我无法在工作表中一致地选择复制的表。
是否有可能以某种方式设置复制的表名称 复制粘贴方法?
我在想类似于
的东西 tbl.Range.Copy Destination:=Sheets("Summary").Range("B" & lr) Name:="t_sum2"
^但这显然不起作用
答案 0 :(得分:2)
你可以参考与范围相交的listobject - 所以如果我们为目标使用范围变量,我们可以参考listobject并重命名它,具体来说:
Private Sub prev_comments_button_Click()
Dim tbl As ListObject
Dim lr As Integer
Dim rng As Range
Set tbl = Sheets("Summary").ListObjects("t_sum")
lr = get_tbl_size + 2 ' gets the table size of the current table _
and we move by two rows, to indent the copied table
Set rng = Sheets("Summary").Range("B" & lr)
tbl.Range.Copy rng
rng.ListObject.Name = "Copied Table"
End Sub
答案 1 :(得分:1)
有很多方法可以做到这一点。我能想到的最简单的方法是将第二个表分配给ListObject并更改ListObject
的名称。像这样:
Option Explicit
Sub CopyTable()
Dim tbl As ListObject
Dim lr As Long
Dim newTbl As ListObject
Set tbl = Worksheets(1).ListObjects("Table1")
tbl.Range.Copy Destination:=Worksheets(1).Range("C20")
Set newTbl = Worksheets(1).ListObjects(2)
newTbl.Name = "Gosho"
End Sub
但是,它总是会更改工作表中第二个表的名称,并且这并不总是您要复制的名称。
以下是一些解决方法,设置新表的特定范围,从而将其分配给正确的ListObject
:
Option Explicit
Sub CopyTable()
Dim tbl As ListObject: Set tbl = ActiveSheet.ListObjects("Table1")
Dim wks As Worksheet: Set wks = Worksheets(1)
Dim tblRange As Range: Set tblRange = tbl.Range
Dim newTbl As ListObject
Dim newTblRange As Range
Dim rngToCopy As Range: Set rngToCopy = Range("A20")
Set newTblRange = wks.Range(rngToCopy, _
rngToCopy.Offset(tblRange.Rows.Count, tblRange.Columns.Count))
tbl.Range.Copy Destination:=rngToCopy
Set newTbl = newTblRange.ListObject
newTbl.Name = "Goshkata be"
End Sub