Reputation: 3
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?
Upvotes: 0
Views: 10663
Reputation: 2119
Try the following. Changes include:
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
Upvotes: 1