VBA错误:应用程序定义或对象定义错误

时间:2014-05-15 11:56:39

标签: excel vba excel-vba

嘿我在excel中收到此错误:应用程序定义的对象定义错误

Private Sub CommandButton1_Click()
Dim r1 As Range
Dim r2 As Range
Dim a As Integer
Dim b As Integer
b = 1

Set r2 = Range("a1:a100")

For Each r1 In r2.Cells
   If r1.Value = "hummer1" Then
    a = r1.Row
    Range(Cells(a, 1), Cells(a, 5)).Copy
    Sheets("Sheet2").Range(Cells(b, 1), Cells(b, 1)).Paste    "line with the error"
    b = b + 1
   End If
Next r1

End Sub

看起来非常简单,但我无法弄清楚问题是什么

3 个答案:

答案 0 :(得分:2)

提及工作表以获得清晰的代码非常重要。以下工作提供您不使用公式,并且不希望更新第二个工作表:

Dim r1 As Range
Dim r2 As Range
Dim a As Integer
Dim b As Integer
b = 1
Dim wkSheet1 As Worksheet
Dim wkSheet2 As Worksheet

Set wkSheet1 = ThisWorkbook.Worksheets("Sheet1")
Set wkSheet2 = ThisWorkbook.Worksheets("Sheet2")
Set r2 = wkSheet1.Range("a1:a100")

For Each r1 In r2.Cells
  If r1.Value = "hummer1" Then
    a = r1.Row
    wkSheet1.Range(wkSheet1.Cells(a, 1), wkSheet1.Cells(a, 5)).Copy
    wkSheet2.Range(wkSheet2.Cells(b, 1), wkSheet2.Cells(b, 5)).PasteSpecial Paste:=xlPasteValues
    b = b + 1
  End If
Next r1

顺便说一句,使用"工作表"而不是" sheet&#34 ;: sheet对象指向图形表和普通表。既然你知道要粘贴在通常的工作表上,那么提及它会使代码更具可读性!

答案 1 :(得分:0)

无法检查,但我认为Paste方法仅适用于Worksheets Object 所以为了使它工作,删除它并执行这样的直接复制:

Range(Cells(a, 1), Cells(a, 5)).Copy Sheets("Sheet2").Range(Cells(b, 1), Cells(b, 1))

此外,由于r2被声明为Range个对象,因此您的For Each Loop应该像以下一样简单:

For Each r1 In r2
    '~~> rest of code here
Next

答案 2 :(得分:0)

这可以解决您的问题:

Private Sub CommandButton1_Click()
Dim r1 As Range
Dim r2 As Range
Dim a As Integer
Dim b As Integer
b = 1

Set r2 = Range("a1:a100")

For Each r1 In r2.Cells
If r1.Value = "hummer1" Then
a = r1.Row
Range(Cells(a, 1), Cells(a, 5)).Copy Destination:=Sheets("Sheet2").Range("A" & b)
b = b + 1
End If
Next r1

End Sub