简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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