简体   繁体   English

Excel Vba:使用表名称作为变量

[英]Excel Vba: Using table name as a variable

I am trying to copy the contents of one table to another. 我正在尝试将一个表的内容复制到另一个表。 in the process I am copying only some columns. 在此过程中,我仅复制一些列。 Sorry if my question is too basic as I'm new to Excel VBA 抱歉,如果我的问题太基础了,因为我是Excel VBA的新手

Dim tableName As ListObject
Set tableName = Worksheets("DataSource").ListObjects(1)
[Table1[TaskUID]].Copy [tableName[TaskUID]]

Line 3 is throwing an error "Object Required" 第3行抛出错误“需要对象”

Could anyone please help with the syntax 任何人都可以帮助语法

The reason it does not work is because using the brackets, [] , is like calling Application.Evaluate() on the expression inside the brackets, so you cannot use your local variable names in there because the thing that will be evaluating the expression has no idea about them. 它不起作用的原因是因为使用方括号[]就像在方括号内的表达式上调用Application.Evaluate()一样,因此您无法在其中使用局部变量名称,因为将要评估表达式的事物具有对他们一无所知。 It cannot find a list object named tableName . 它找不到名为tableName的列表对象。

You can avoid the brackets (arguably, you always should): 您可以避免使用方括号(可以说,您应该总是这样):

Dim tableName As ListObject
Set tableName = Worksheets("DataSource").ListObjects(1)

ListObjects("Table1").ListColumns("TaskUID").DataBodyRange.Copy tableName.ListColumns("TaskUID").DataBodyRange

With actual table names: 使用实际的表名:

You can wrap with Range and use the actual table names. 您可以使用Range换行并使用实际的表名。 You are effectively calling the .Copy method on a named range. 您实际上是在命名范围上调用.Copy方法。 So if they were in the same sheet for example: 因此,例如,如果它们在同一张纸中:

With ActiveSheet

    .Range("Table1[TaskUID]").Copy .Range("Table2[TaskUID]")

End With

You can always qualify the destination with the sheet name if it is in another sheet. 如果目的地在另一个工作表中,则始终可以使用工作表名称限定目的地。

Or (by column number of table variable): 或(按表变量的列号):

As you need a range to be used for the copy destination, if you know the column number of the table variable to paste to, you can also write, using the table variable name something like: 由于您需要一个范围用于复制目标,因此,如果您知道要粘贴到的表变量的列号,则还可以使用表变量名称来编写,例如:

.Range("Table1[TaskUID]").Copy  tableName.DataBodyRange.Columns(2) 'or which ever column

Or (by column name of table variable): 或(按表变量的列名):

.Range("Table1[TaskUID]").Copy tableName.ListColumns("TaskUID").DataBodyRange

You could place tableName.ListColumns("TaskUID").DataBodyRange in its own variable and then refer to that eg 您可以将tableName.ListColumns("TaskUID").DataBodyRange放在其自己的变量中,然后引用该变量,例如

Dim rng As Range
Set rng = tableName.ListColumns("TaskUID").DataBodyRange

.Range("Table1[TaskUID]").Copy rng

Edit: As GSerg points out you can't use the variable name inside. 编辑:正如GSerg指出的,您不能在其中使用变量名。 "Range will not be able to find a table named tableName because that is the name of a variable, not of a table" “范围将无法找到名为tableName的表,因为这是变量而不是表的名称”

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

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