简体   繁体   中英

What is wrong with this code that generates an error?

I don't know what is wrong with this code, could someone please spot the mistake?. Igives me the error:

object does not support this property or method.

Sub copyrow2()

Dim Lastro As Integer
Dim nLastro As Integer
Dim Rng As Range

nLastro = ActiveSheet.Cells(Rows.Count, 10).End(xlUp).Row
Lastro = ActiveSheet.Cells(Rows.Count, 9).End(xlUp).Row + 1

If Lastro < nLastro Then

With oSht = ActiveSheet
Set Rng = oSht.Range("J" & Lastro & ":" & "k" & nLastro)
      Rng.Copy
      oSht.Range("H" & Lastro).Select
      ActiveSheet.Paste
End With

End If

There are couple of problems with the code

  1. Please use Option Explicit . That will force you to declare variables. For example oSht is undeclared.
  2. When working with rows, never declare tham as Integers . There is a huge possibility that you may get an error in xl2007+. Declare them as Long
  3. Avoid the use of ActiveSheet/Select etc. INTERESTING READ
  4. Fully qualify Rows.Count . When working with several excel files in compatibility mode, it could result in an error if you don't fully qualify them.

Is this what you are trying?

Code: (untested)

Option Explicit

Sub copyrow2()
    Dim oSht As Worksheet
    Dim Lastro As Long, nLastro As Long
    Dim Rng As Range

    '~~> Change this to the relevant sheet
    Set oSht = ThisWorkbook.Sheets("Sheet1")

    With oSht
        nLastro = .Cells(.Rows.Count, 10).End(xlUp).Row
        Lastro = .Cells(.Rows.Count, 9).End(xlUp).Row + 1

        If Lastro < nLastro Then
            Set Rng = .Range("J" & Lastro & ":" & "k" & nLastro)
            Rng.Copy .Range("H" & Lastro)
        End If
    End With
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