简体   繁体   English

嵌套用于引用表的循环的Excel VBA构造

[英]Excel VBA construct nested for loops to reference tables

I have a two pivot tables constructed from some data (without the same structure), and I need to compare each entry using the Cartesian product of some other tables. 我有两个由一些数据(没有相同结构)构成的数据透视表,我需要使用其他一些表的笛卡尔积来比较每个条目。

I'd like to have some nested for loops in VBA which grab data from the pivot tables based on some lists I've constructed. 我想在VBA中嵌套一些for循环,这些循环基于我构建的一些列表从数据透视表中获取数据。

My Lists: 我的清单:

+------+-----+
| Date | ID  |
+------+-----+
| 9/1  | 123 |
| 9/2  | 124 |
| 9/3  | 200 |
| 9/4  | 201 |
|      | 202 |
|      | 300 |
|      | 500 |
|      | 999 |
+------+-----+

I can't figure out how to reference each entry in each column in these lists to use them in a command. 我不知道如何引用这些列表中的每一列中的每个条目以在命令中使用它们。 I have in mind something like the following: 我想到的是以下内容:

for each day in Date:
  for each num in ID:
    do_pivot_fetch(from pivot1, date=day, ID=num)

If these lists are maintained in Excel (this is how I always write these things, that way it's easy to change parameters when you need to), I usually use do...while to iterate over them. 如果这些列表是在Excel中维护的(这就是我总是写这些东西的方式,那么在需要时可以轻松更改参数),我通常使用do ... while对其进行迭代。 You can also try to find the last filled cell in each row and use it to calculate the range of a for loop, but I've found that to be glitchy given the things people like to do with excel spreadsheets. 您还可以尝试在每一行中找到最后一个填充的单元格,并使用它来计算for循环的范围,但是鉴于人们喜欢使用excel电子表格进行的操作,我发现这是一个小问题。

So let's say you have the lists in column A (Date) and B (ID) on sheet 'Params'. 假设您在工作表“ Params”上的A(日期)和B(ID)列中都有列表。 Assuming you have headers in row 1, and an empty row after the last value in each list. 假设您在第1行有标题,并且在每个列表的最后一个值之后有一个空行。 Then your code would look something like this: 然后您的代码将如下所示:

Sub useParams()
Dim Date_val, ID_val As Range
With ThisWorkbook.Worksheets("Params")
    Set Date_val = Range("A2")
    Do While Date_val.Value <> ""
        Set ID_val = Range("B2")
            Do While ID_val.Value <> ""
               //do_pivot_fetch(from pivot1, date=Date_val.Value, ID=ID_val.Value)
               Set ID_val = ID_val.Offset(1, 0)
            Loop
        Set Dateval = Date_val.Offset(1, 0)
   Loop
End With
End Sub

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

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