简体   繁体   English

使用Excel表和VBA在动态列的每一行中循环

[英]Loop through each row in dynamic column using Excel Tables and VBA

I am trying to loop through various elements in a Vertical Excel Table and pass them to a horizontal table using VBA. 我试图遍历垂直Excel表中的各种元素,并使用VBA将它们传递到水平表。 The vertical table is a form that contains a list of questions (name,label,value) and the horizontal table will contain columns using the question name from the vertical table. 垂直表是包含问题列表(名称,标签,值)的表格,水平表将包含使用垂直表中问题名称的列。

The code looks something like this: 代码看起来像这样:

Dim row As Range
Dim rowCount As Integer: rowCount = 1
For Each row In [tbl_QUESTIONS[name]].Rows
  Sheets(ANSWERS).Cells(r,rowCount).Value = row.Value
  rowCount = rowCount + 1
Next

My question is, how can modify the table reference and column reference so that they are dynamic? 我的问题是,如何修改表引用和列引用以使其动态?

[tbl_QUESTIONS[name]].Rows

I would like to be able to do something like this: 我希望能够做这样的事情:

["tbl_" & tblName & "[" & colName & "]]".Rows

But that doesn't seem to work... Is there a simpler way to reference this using VBA? 但这似乎不起作用...是否有更简单的方法使用VBA来引用它? I get the feeling that there has to be a way of creating the ListObject out of ["tbl_" & tblName] but I haven't been able to reference 'colName' inside the ListObject or the ListObject.Rows 我觉得必须要有一种方法可以从[“ tbl_”&tblName]中创建ListObject,但是我无法在ListObject或ListObject.Rows中引用'colName'。

Any help would be appreciated. 任何帮助,将不胜感激。

Oh, and I'd like to keep this compatible with Excel 2007 VBA if at all possible. 哦,我想尽可能与Excel 2007 VBA兼容。

Cheers! 干杯!

I've stumbled upon this link and it seems to do the trick. 我偶然发现了这个链接 ,它似乎可以解决问题。

Looks like I can create a range using the following: 看起来我可以使用以下内容创建范围:

Dim TBL As Range
Set TBL = Range("tbl_" & tblName & "[" & colName & "]")

I'd still like to see a way of keeping the ListObject rather than defining a range, but I'll go with this until I have an alternative. 我仍然希望看到一种保留ListObject而不是定义范围的方法,但是在没有其他选择之前,我将继续进行此操作。

You probably know this by now but since the question has no answer... 您可能现在已经知道了,但是由于问题没有答案...

use the LisObjects collection to select a listObject and pass that as a parameter to your function/sub 使用LisObjects集合选择一个listObject并将其作为参数传递给您的函数/子对象

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

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