[英]How can I set the range of the first listobject in an Excel worksheet to be a variable?
[英]How can I reference a ListObject with a variable?
我在 Excel 中有一个表,它是通过查询 SQL 数据库生成的,所以我最终得到了一个表,其列标题为 A、B、C、D、E。
我想根据用户的选择在 VBA 中填充一个数组。 例如,如果单元格 A1 中有 A,则数组将填充 A 列的数据。如果单元格 A1 中有 B,则数组将填充 B 列的数据,依此类推。
我目前正在尝试使用以下代码:
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
但是在尝试使用字符串变量 A 作为 Listcolumn 中的引用的行上出现错误。
如果我在 A 周围抛出""
它可以工作,但它不是一个变量。 我可以通过对每个给定选项使用 Case 来完成我想要的,但我想让它更加精简。 有没有办法可以使用变量来引用 Listobject,就此而言是 Worksheet 等等?
请尝试以下操作。 变化包括:
代码
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.