简体   繁体   中英

Paste into next empty column in different sheet

my code aims to copy the same range from multiple sheets and paste the data from each sheet into the next empty column in a Combined sheet. My code copies from each sheet correctly, but pastes into the same column and overwrites the preceding paste.

Could someone please point out my error?

Many thanks!

Sub CopyToNextCol()

    Dim Sh As Worksheet
    Dim NextCol As Long

    For Each Sh In ThisWorkbook.Worksheets

        If Sh.Name <> "Master" And Sh.Name <> "Lists" And Sh.Name <> "Combined" Then

          NextCol = Sheets("Combined").Cells(, Columns.Count).End(xlToLeft).Column + 1

          Sh.Range("B2:B44").Copy Sheets("Combined").Cells(, NextCol)

        End If

    Next Sh

End Sub

Copy Same Ranges From Multiple Worksheets

  • The following example will copy the worksheet names ( "I am planning to use a different column header" in the comments) in the first row and each range below it.
  • s - Source, d - Destination.

A Quick Fix

Option Explicit

Sub CopyToNextCol()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim dws As Worksheet: Set dws = wb.Worksheets("Combined")
    Dim dCell As Range
    Set dCell = dws.Cells(1, dws.Columns.Count).End(xlToLeft).Offset(, 1)
    
    Dim sws As Worksheet
    Dim srg As Range
    
    For Each sws In wb.Worksheets
        Select Case sws.Name
        Case "Master", "Lists", "Combined"
            ' Skip (do nothing)
        Case Else
            Set srg = sws.Range("B2:B44")
            dCell.Value = sws.Name
            srg.Copy dCell.Offset(1)
            Set dCell = dCell.Offset(, 1)
        End Select
    Next sws

    'wb.Save

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM