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

时间:2018-07-18 18:44:37

标签: excel vba excel-vba

我希望遍历工作表并根据某些索引创建表。基本上,我的表的结构如下:

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

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

我只是希望编写一个代码,该代码将遍历工作表并为要注释的每个ID创建一个表。我包括指向显示初始表以及所需代码结果的屏幕快照的链接。

之前: Before

之后: After

再次感谢您的建议。

1 个答案:

答案 0 :(得分:0)

这是一个高度定制的解决方案。它假定表始终为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