0

I tried to select and copy from Sheet 4 to Sheet 5 till the end of the list on Sheet 4.

It works one time only, not looping, and giving me an error message

"pasteSpecial method of worksheet class failed"

Code:

Sub SelectBetween()

i = 1

Sheets("Sheet4").Activate

Do Until i > 63

    Dim findrow As Long, findrow2 As Long

    findrow = Range("A:A").Find("Department", Range("A1")).Row
    findrow2 = Range("A2:A3141").Find("Department", Range("A" & findrow)).Row
    Range("A" & findrow & ":A" & findrow2 - 1).Select

    Selection.Cut Sheets("Sheet5").Cells(2, Columns.Count).End(xlToLeft).Offset(, 1)

    ActiveSheet.PasteSpecial Link:=True
    Application.CutCopyMode = False

    i = i + 1

Loop

End Sub
cokeman19
  • 2,405
  • 1
  • 25
  • 40
A-S
  • 9
  • 1

2 Answers2

0

Try this.

Learn to avoid Select/Activate.

When using Find check the item is found before trying to access properties such as Row to avoid errors. And good practice to specify all its parameters.

You can use a For loop here as you know the endpoint.

Sub SelectBetween()

Dim i As Long

For i = 1 To 63
    Dim findrow As Range, findrow2 As Range
    With Sheets("Sheet4")
        Set findrow = .Range("A:A").Find(what:="Department",after:=.Range("A1"))
        If Not findrow Is Nothing Then
            Set findrow2 = .Range("A2:A3141").Find(what:="Department", after:=findrow)
            If Not findrow2 Is Nothing Then
                .Range(findrow, findrow2.Offset(-1)).Cut
                Sheets("Sheet5").Cells(2, Columns.Count).End(xlToLeft).Offset(, 1).PasteSpecial Link:=True
            End If
        End If
    End With
Next i

End Sub
SJR
  • 22,986
  • 6
  • 18
  • 26
0

It worked well by the below code. only deleted the below lines from the previous code.

ActiveSheet.PasteSpecial Link:=True Application.CutCopyMode = False

Sub SelectBetween()

i = 1

Sheets("Sheet4").Activate

Do Until i > 63


    Dim findrow As Long, findrow2 As Long


    findrow = Range("A:A").Find("Department", Range("A1")).Row
    findrow2 = Range("A2:A3141").Find("Department", Range("A" & findrow)).Row
    Range("A" & findrow & ":A" & findrow2 - 1).Select

    Selection.Cut Sheets("Sheet5").Cells(2, Columns.Count).End(xlToLeft).Offset(, 1)


     i = i + 1

    Loop

End Sub
A-S
  • 9
  • 1