简体   繁体   中英

How can I reference a ListObject with a variable?

I have a table in Excel that is generated by querying an SQL database, so I end up with a table that has column titles of, say, A, B, C, D, E.

I want to populate an array in VBA based on the user's selection. For example, if Cell A1 has A in it, the array will be populated with the data from Column A. If the Cell A1 has B in it, the array will be populated with the data from Column B and so on.

I am currently trying to use the following code:

Sub Compare()

    Dim WS As Worksheet
    Dim lo As ListObject
    Dim Xaxis As Variant
    Set WS = Worksheets("SQL Table") 'sheet that has SQL generated table
    Set lo = WS.ListObjects("Table") 'Table is the name of the table

    Dim A As String

    A = WS.Range("A1").Value 'A1 in this case has the value A in it
    Xaxis = Worksheets("SQL Table").ListObjects("Table").ListColumns(A).DataBodyRange

End Sub

but get an error on the line that attempts to use the string variable A as a reference in a Listcolumn.

If I throw "" around A it works, but then it's not a variable. I can accomplish what I want by using Case for each of the give options, but I would like to make it more streamlined. Is there a way I can use a variable to reference a Listobject, for that matter a Worksheet and so on?

Try the following. Changes include:

  • Dim'd Xaxis as Range
  • Use Set keyword
  • Took advantage of the objects already constructed

The code

Sub Compare()

Dim WS As Worksheet
Dim lo As ListObject
Dim Xaxis As Range
Set WS = Worksheets("SQL Table") 'sheet that has SQL generated table
Set lo = WS.ListObjects("Table") 'Table is the name of the table

Dim A As String

A = WS.Range("A1").Value 'A1 in this case has the value A in it
Set Xaxis = lo.ListColumns(A).DataBodyRange

End Sub

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