简体   繁体   English

如何将Excel工作表中第一个列表对象的范围设置为变量?

[英]How can I set the range of the first listobject in an Excel worksheet to be a variable?

I have a macro in Excel that I use to alter and process data in a table. 我在Excel中有一个宏,可用于更改和处理表中的数据。 I'm trying to make it less specific in the table that it affects. 我正在尝试使其在影响的表中不太具体。 When I need to search through the table, my macro explicitly references the table name and sometimes the specific table header like so: 当我需要搜索表时,宏会显式引用表名,有时还会引用特定的表头,如下所示:

Range("productUpdate[id]")

I want my macro to be able to handle table's that do not match that specific criteria. 我希望我的宏能够处理与特定条件不匹配的表。 I figured I could assign the name to a variable, but I don't know to get the data I need. 我想可以将名称分配给变量,但是我不知道如何获取所需的数据。 How would I accomplish this? 我将如何完成?

My criteria for finding the information: 我查找信息的标准:

  • The table's name could be anything. 桌子的名字可以是任何东西。
  • The first column header could be named anything. 第一列标题可以命名为任何东西。
  • The table is always going to be the first table/listobject in the worksheet. 该表将始终是工作表中的第一个表/列表对象。

You can use string concatenation. 您可以使用字符串串联。 Range(tblN & "[" & colN & "]") where tblN and colN are string variables with the table name and column name. Range(tblN & "[" & colN & "]")其中tblNcolN是具有表名和列名的字符串变量。

Presuming I understand your question correctly, you can refer point a variable to the first table in the worksheet as such: 假设我正确理解了您的问题,您可以这样将变量指向工作表中的第一个表:

Sub Testit()
    Dim tbl As ListObject

    Set tbl = Sheet1.ListObjects(1)
End Sub

From there, you can reference the tables properties as needed. 从那里,您可以根据需要引用表属性。 Examples follow: 示例如下:

MsgBox tbl.Name
MsgBox tbl.ListColumns.Count
MsgBox tbl.ListColumns(2).Name

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

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