基于多个工作表创建摘要表

时间:2015-09-12 16:57:58

标签: excel vba excel-vba

我有许多工作表包含相同的结构和相同的行数。现在我想创建一个主表来概述使用VBA的所有工作表。

它就像一张资产负债表,显示了几年来的表现,其中几年是标题,项目是行。

现在,年度数据被放在名为“2012”,“2013”​​和“2014”的多个工作表上。

表1(“2012”)上的B列将被复制到“master”上的col B上,但是对于以下表格(“2013”​​,“2014”),数据将被放置在“master”的下一列上(即2013年关于col C的数据,2014年关于col D的数据)。

我希望有一个可用的宏,可以计算工作表的数量,并在主工作表的右栏上复制粘贴特定数据。

1 个答案:

答案 0 :(得分:0)

1)在表格中创建一个表格:第一列是主报表中目标单元格的位置。第二列是数据的复制位置。

enter image description here

2)将所有工作表放在一个文件夹中

3)运行此宏,需要将其置于主模块

Option Explicit

'assuming that:
'- "Excel Column Code" is in column A
'- "Form Cell Code" is in column B
'in zmaster.xlsm!Sheet2


Sub UpdateData()
Dim sFile As String, sPath As String
Dim srcWbk As Workbook, dstWbk As Workbook
Dim srcWsh As Worksheet, dstWsh As Worksheet, infoWsh As Worksheet
Dim i As Long, j As Long, k As Long

On Error GoTo Err_UpdateData


Set dstWbk = ThisWorkbook
Set dstWsh = dstWbk.Worksheets("Sheet1")
Set infoWsh = dstWbk.Worksheets("Sheet2")

sPath = "C:\Desktop\New folder\"
sFile = Dir(sPath)
Do While Len(sFile) > 0
    If sFile = "zmaster.xlsm" Then
    GoTo SkipNext
    End If

    Set srcWbk = Workbooks.Open(sPath & sFile)
    Set srcWsh = srcWbk.Worksheets(1)
    i = 2
    'loop through the information about copy-paste method
    Do While infoWsh.Range("A" & i) <> ""
        'get first empty row, use "Excel Column Code" to get column name
        j = GetFirstEmpty(dstWsh, infoWsh.Range("A" & i))
        'copy data from source sheet to the destination sheet
        'use "Form Cell Code" to define destination cell
        srcWsh.Range(infoWsh.Range("B" & i)).Copy dstWsh.Range(infoWsh.Range("A" & i) & j)
        i = i + 1
    Loop
    srcwbk.Close SaveChanges:=False
SkipNext:
    sFile = Dir
Loop

Exit_UpdateData:
    On Error Resume Next
    Set srcWsh = Nothing
    Set dstWsh = Nothing
    Set srcWbk = Nothing
    Set dstWbk = Nothing
    Exit Sub

Err_UpdateData:
    MsgBox Err.Description, vbExclamation, Err.Number
    Resume Exit_UpdateData
End Sub




'returns first empty row in a destination sheet based on column name
Function GetFirstEmpty(ByVal wsh As Worksheet, Optional ByVal sCol As String = "A") As Long

GetFirstEmpty = wsh.Range(sCol & wsh.Rows.Count).End(xlUp).Row + 1

End Function