从多个工作表创建摘要表

时间:2018-03-10 13:01:31

标签: excel excel-vba vba

问题

我想遍历所有工作表并创建摘要表。我有一个动态列,而某些标题位于COLUMN X,而某些标题位于COLUMN AG

因此,我决定获取特定的标题名称,而不是选择特定的列,以解决该问题。

但是,我似乎无法在我的代码上取得进展,因为我不知道如何在整个工作表中循环,获取列然后将其添加到摘要中。

CODE

Public Sub forSummary()
Dim ws As Worksheet
Dim lRow As Long
Dim aCell As Range, rng1 As Range

'~~> Set this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("JAN 6")

With ws
    '~~> Find the cell which has the name
    Set aCell = .Range("A1:BA1").Find("TOTAL OUT")

    '~~> If the cell is found
    If Not aCell Is Nothing Then
        '~~> Get the last row in that column and check if the last row is > 1
        lRow = .Range(Split(.Cells(, aCell.Column).Address, "$")(1) & .Rows.Count).End(xlUp).Row

        If lRow > 1 Then
            '~~> Set your Range
            Set rng1 = .Range(aCell.Offset(1), .Cells(lRow, aCell.Column))
            '~~> This will give you the address
            rng1.Select
        End If
    End If
End With
End Sub

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的代码中的问题是您将ws设置为特定工作表。相反,循环遍历工作表集合并以这种方式完成工作。

Dim ws As Worksheet, tempRng As Range

For Each ws In ThisWorkbook.Worksheets

    Set tempRng = ws.Range()    'Set your range you need for your summary page

    ' Code to perform actions with your range

    Set tempRng = Nothing

Next ws