简体   繁体   English

Excel VBA-遍历电子表格基于查询创建表

[英]Excel VBA - loop through spreadsheet creating tables based on query

I'm hoping to loop through a worksheet and create Tables based on certain indexes. 我希望遍历工作表并根据某些索引创建表。 Essentially my table is structured as follows: 本质上,我的表的结构如下:

ID | 101
Date | 2018-07-18
Product | Banana
Comments | 

ID | 102
Date | 2018-07-18
Product | Apple
Comments |

And I'm just hoping to write a code that will loop through the worksheet and make one Table for every ID to Comments. 我只是希望编写一个代码,该代码将遍历工作表并为要注释的每个ID创建一个表。 I'm included links to screenshots showing my initial table, and the desired outcome of the code. 我包括指向显示初始表和所需代码结果的屏幕快照的链接。

Before: 之前: 之前

After: 后: 后

Thanks again for your advice. 再次感谢您的建议。

Here's a highly customized solution. 这是一个高度定制的解决方案。 It assumes table always 4 rows and two columns. 假定表始终为4行两列。

Sub easyGoofy()
Dim WS As Worksheet, rCell As Range, i As Integer, rStart As Long

For Each WS In ActiveWorkbook.Sheets
i = 0
rStart = 1

startSearch:
    If Not Intersect(WS.UsedRange.Cells, WS.Rows(rStart & ":" & Rows.Count)) Is Nothing Then

        For Each rCell In Intersect(WS.UsedRange.Cells, WS.Rows(rStart & ":" & Rows.Count)).Cells
            If UCase(rCell.Value) = "ID" And UCase(rCell.Offset(1, 0).Value) = "DATE" Then

                WS.ListObjects.Add(xlSrcRange, Range(rCell, rCell.Offset(3, 1)), , xlYes).Name = "TBL_" & i
                rStart = WS.ListObjects("TBL_" & i).DataBodyRange.Rows.Count + 1 + rStart
                 i = i + 1

                GoTo startSearch

            End If
        Next rCell

    End If

Next WS

End Sub

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

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