我正在编写一些代码来将多个工作表(它们构成各个零件清单)合并为一个大型零件清单。从VBA中排除1行复制范围
到目前为止,我有2个功能,其扫描每个工作表的最后行和列
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
和
Function LastCol(sh As Worksheet)
On Error Resume Next
LastCol = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
然后我有它创建了一个名为“零件清单”新的工作表另一个子并在那里粘贴范围。
Sub CopyRangeFromMultiWorksheets()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim CopyRng As Range
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
' Delete the summary sheet if it exists.
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Parts List").Delete
On Error GoTo 0
Application.DisplayAlerts = True
' Add a new summary worksheet.
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "Parts List"
' Loop through all worksheets and copy the data to the
' summary worksheet.
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
' Find the last row with data on the summary worksheet.
Last = LastRow(DestSh)
' Specify the range to place the data.
' Set CopyRng = sh.Range("B3:G10").
Set CopyRng = sh.UsedRange
' Test to see whether there are enough rows in the summary
' worksheet to copy all the data.
If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
MsgBox "There are not enough rows in the " & _
"summary worksheet to place the data."
GoTo ExitTheSub
End If
' This statement copies values and formats from each
' worksheet.
CopyRng.Copy
With DestSh.Cells(Last + 1, "A")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
' Optional: This statement will copy the sheet
' name in the H column.
DestSh.Cells(Last + 1, "I").Resize(CopyRng.Rows.Count).Value = sh.Name
End If
Next
ExitTheSub:
Application.Goto DestSh.Cells(1)
' AutoFit the column width in the summary sheet.
DestSh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
我遇到的问题是使用范围复制标题行。有谁知道如何从行和列扫描中排除标题或被复制?
感谢所有帮助 丹
标题行固定在位置上,还是它们在单元格类型上有所不同?文本与数字例如?如果你分享你的工作表的样子,这将是有帮助的。 – Luuklag
我已经添加了部件列表的图片(我想删除突出显示为橙色的行)以及每个工作表的外观如何的示例 –
问题与您的复制方式有关。您可以选择工作表中的所有内容并一次全部复制。 Robin Mackenzie的代码将删除第一行,但这在您的示例中不够用。我个人会遍历所有行,并检查单元格A行中的值是否为数字。如果数字则复制,否则下一行。然而,这可能会非常消耗CPU使用量。因此,您必须使用我描述的循环机制以不同的方式定义范围。 – Luuklag