【发布时间】:2017-10-11 21:09:03
【问题描述】:
所以我拼凑了这个子项,它在我的工作簿中的所有选项卡中查找特定名称,然后将所有数据复制到下一个空行的单个工作表中。
基本上是组合一堆具有相同列格式的相似工作表。
所以我的问题是如何修改它以遍历多组工作表?目前,这被编码为仅适用于名为“Group1”的工作表并复制到名为“raw_Group1”的单个工作表中。
我如何修改以同时查找“Group2”,...“GroupN”?分组名称实际上并没有编号,而是像“人”“东西”“订单”等。每个组都有不同的列结构和我试图组合的多个工作表。
Sub copy_Group1()
Dim ws As Worksheet
Dim Destws As Worksheet
Dim Last As Long
Dim wsLast As Long
Dim CopyRng As Range
Dim StartRow As Long
'This keeps the screen from updating until the end, makes the macro run faster
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'defines an existing "Raw_Group1" worksheet instead of creating a new one
Set Destws = ActiveWorkbook.Sheets("Raw_Group1")
'clears sheet first, leaving headers
Destws.Rows("2:" & Rows.Count).ClearContents
'Fill in the start row.
StartRow = 2
'Loop through all worksheets and copy the data to the summary worksheet.
For Each ws In ActiveWorkbook.Worksheets
If LCase(ws.Name) Like "group1*" Then
'Find the last row with data on the summary and source worksheets.
Last = LastRow(Destws)
wsLast = LastRow(ws)
'If source worksheet is not empty and if the last row >= StartRow, copy the range.
If wsLast > 0 And wsLast >= StartRow Then
'Specify the range to place the data. Four options for specifying the range
''Set CopyRng = sh.Range("A1:G1") 'whole block of columns
''Set CopyRng = ws.Range("A1:B" & LastRow) 'specific columns, to the last row
''Set CopyRng = ws.Range("B1").CurrentRegion 'uses the current block of data
Set CopyRng = ws.Range(ws.Rows(StartRow), ws.Rows(wsLast)) 'Set the range starting at row2
'Test to see whether there are enough rows in the summary worksheet to copy all the data.
If Last + CopyRng.Rows.Count > Destws.Rows.Count Then
MsgBox "There are not enough rows in the " & _
"summary worksheet to place the data."
GoTo ExitTheSub
End If
CopyRng.Copy ' This statement copies values and formats.
'paste values only
With CopyRng
Destws.Cells(Last + 1, "A").Resize(.Rows.Count, _
.Columns.Count).Value = .Value
End With
End If
End If
Next
ExitTheSub:
Application.Goto Destws.Cells(1)
'filter: turns off then on (resets)
If Destws.AutoFilterMode Then Destws.AutoFilterMode = False
Destws.Range("A1").AutoFilter
'AutoFit the column width in the summary sheet.
Destws.Columns.AutoFit
'turns screen updating back on
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
修改此行
If LCase(ws.Name) Like "group1*" Then -
这似乎只是改变了 if 语句的其余部分正在寻找的组。我问的是添加更高级别的循环来迭代 group1、group2、groupn 等。我当然可以重复整个事情,但要寻找更简洁的代码。我仍在尝试学习如何设置此语法
-
为每个不同的组使用案例选择。你甚至可以像 "People1*" 这样的案例 LCase(ws.Name) 。
-
就像将我的组名列表添加为数组或其他东西,然后从第一个到最后一个迭代,运行代码(定义目标并复制/粘贴每个匹配表)