Search code examples
vbaexcelexcel-2010copy-paste

I am trying to copy row heights from one sheet to another sheet


I am trying to copy row heights from one sheet1 to sheet2. but the following code is not working. note that the tables on both sheets are on different row numbers as well.

Call Unhide

With Sheet1

    Dim LastRowC23 As Integer
    LastRowC23 = Application.WorksheetFunction.Match("CYCLE 1", 
    .Range("A:A"), 0) - 1

    Dim LastRow As Integer
    LastRow = .Cells(.Rows.count, "B").End(xlUp).Row

    .Range("A3:BD3"), 0)

    Dim C1StartCol As Integer
    C1StartCol = Application.WorksheetFunction.Match("CYCLE 1", 
    .Range("A1:BD1"), 0)

    Dim C2StartCol As Integer
    C2StartCol = Application.WorksheetFunction.Match("CYCLE 2", .Range("A1:BD1"), 0)

    Dim LastCol As Integer
    LastCol = .Cells(3, .Columns.count).End(xlToLeft).Column

    Sheet2.Range("A1:CZ200").Clear

    .Range("A1", .Cells(3, C2StartCol - 1)).Copy
    Sheet2.Range("A1").PasteSpecial xlPasteAllUsingSourceTheme
    Sheet2.Range("A1").PasteSpecial xlPasteColumnWidths
    .Range(.Cells(LastRowC23 + 1, 1), .Cells(LastRow - 1, C2StartCol - 1)).Copy
    Sheet2.Range("A4").PasteSpecial xlPasteAllUsingSourceTheme
    Sheet2.Range("A4").PasteSpecial xlPasteColumnWidths

    Dim i As Integer
    Dim count As Integer

    count = 4

    For i = LastRowC23 + 1 To LastRow
        .Rows(count).RowHeight = Sheet2.Rows(i).RowHeight
        count = count + 1
    Next i



    Sheet2.Outline.ShowLevels ColumnLevels:=1

End With

The following is the part specific to row heights. Here, I am going through each row in the sheet 1 portion and making the sheet 2 row heights equal to the sheet 1 row heights.

    Dim i As Integer
    Dim count As Integer

    count = 4

    For i = LastRowC23 + 1 To LastRow
        .Rows(count).RowHeight = Sheet2.Rows(i).RowHeight
        count = count + 1
    Next i

Solution

  • You are inside a With ... End With block that references sheet1 as the parent worksheet. LastRowC23 and LastRow are defined by row locations on sheet1. Count is arbitrarily assigned a value of 4.

    If you are 'making the sheet 2 row heights equal to the sheet 1 row heights', then you seem to be using everything backwards.

    For i = LastRowC23 + 1 To LastRow
        Sheet2.Rows(count).RowHeight = .Rows(i).RowHeight
        count = count + 1
    Next i