Excel宏中的运行时错误1004:应用程序定义的错误或对象定义的错误

时间:2017-03-18 16:11:56

标签: excel vba excel-vba

我试图使用此代码在一张纸上搜索某些内容并将其移至另一张纸中。以下是我的代码。我一直收到这个错误:

       Run-time error '1004':
       Application-defined or object-defined error

代码:

Private Sub CommandButton1_Click()
    Dim ws As Worksheet, myCounter
    Dim erow, myValue As Long

    For Each ws In Sheets

    If ws.Range("C3").Value > 6 Then

    myCounter = 1
    ws.Select
    ws.Range("C3").Select

    myValue = ws.Range("C3").Value

    Worksheets("Report").Select

    erow = ActiveSheet.Cells(Rows.Count, 1).End(x1Up).Offset(1, 0).Row

    ActiveSheet.Cells(erow, 1) = myValue

    nextValue = MsgBox("Value found in " & ws.Name & Chr(10) & "Continue?",       vbInformation + vbYesvbNo, ws.Name & " C3 = " & ws.Range("C3").Value)

    Select Case nextValue
    Case Is = vbYes
    Case Is = vbNo
    Exit Sub
    End Select
    End If
    Next ws

    If myCounter = 0 Then
        MsgBox "None of the sheets contains a " & Chr(10) & "value greater than 6 in cell C3 ", vbInformation, "Not Found"
    End If

End Sub

为什么我收到此错误?

       **Run-time error '1004':
       Application-defined or object-defined error**

1 个答案:

答案 0 :(得分:1)

你有x1Up你应该xlUp;请注意1而不是小写L。 MsgBox选项也是vbYesNo,而不是vbYesvbNo

Option Explicit

Private Sub CommandButton1_Click()
    Dim w As Long, bFound As Boolean, nextValue As Variant
    Dim erow, myValue As Long

    For w = 1 To Worksheets.Count
        With Worksheets(w)
            'don't look on the Report worksheet
            If .Name <> Worksheets("Report").Name Then
                'use isnumeric to avoid confusing text and numbers
                If IsNumeric(.Range("C3").Value2) Then
                    If .Range("C3").Value2 > 6 Then
                        Worksheets("Report").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = .Range("C3").Value
                        nextValue = MsgBox("Value found in " & .Name & Chr(10) & "Continue?", vbInformation + vbYesNo, .Name & " C3 = " & .Range("C3").Value)
                        bFound = True
                        Select Case nextValue
                            Case vbYes
                                'do nothing; continue
                            Case vbNo
                                'just exit the worksheet loop
                                Exit For
                        End Select
                    End If
                End If
            End If
        End With
    Next w

    If Not bFound Then
        MsgBox "None of the sheets contains a " & Chr(10) & "value greater than 6 in cell C3 ", vbInformation, "Not Found"
    End If

End Sub

以上是我的代码版本。习惯使用Option Explicit来避免拼写错误。