簡體   English   中英

產生錯誤的代碼有什么問題?

[英]What is wrong with this code that generates an error?

我不知道這段代碼有什么問題,有人可以找出錯誤嗎? 給我這個錯誤:

對象不支持此屬性或方法。

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

代碼有幾個問題

  1. 請使用Option Explicit 這將迫使您聲明變量。 例如,未聲明oSht
  2. 處理行時,切勿將tham聲明為Integers xl2007 +中很可能會出現錯誤。 將它們聲明為Long
  3. 避免使用ActiveSheet/Select等。 有趣的閱​​讀
  4. 完全限定Rows.Count 在兼容模式下使用多個excel文件時,如果您不完全限定它們可能會導致錯誤。

這是您要嘗試的嗎?

代碼:(未經測試)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM