我正在编写一个宏来将范围从多个工作表(在同一工作簿中)复制到工作簿中新工作表中的列。我希望在第一张纸的范围(“C2:C12021”)中的值被复制到新纸张中的A列,然后是从第二张纸到B列的范围内的值(“C2:C12021”)新表等。
我目前正在使用以下代码,但是宏会不断地将我尝试组合的每个工作表的范围复制到我尝试将它们组合在一起的工作表的同一列中。
因此,只有最后一张纸的范围出现在合并纸张中,我认为这是从其他纸张复制的范围被简单地覆盖的情况,因为宏在纸张中循环。
Sub CombineWorksheets()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim CopyRng As Range
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("MergeSheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'Add a worksheet named "MergeSheet"
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "MergeSheet"
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
'Copy target range
Set CopyRng = sh.Range("C2:C12021")
CopyRng.Copy
With DestSh.Cells(Last + 1, "A")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
End If
Next
End Sub
答案 0 :(得分:1)
您可以将单元格的水平值引用为整数,即
.Cells(Vertical As Integer, Horizontal As Integer)
所以在循环开始时,有一个计数器变量,并在水平值中使用它。
Dim count As Integer
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
count = count + 1
'Copy target range
Set CopyRng = sh.Range("C2:C12021")
CopyRng.Copy
With DestSh.Cells(last + 1, count)
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
End If
Next