运行时错误'1004'应用程序定义的错误或对象定义的错误。 VBA EXCEL

时间:2014-01-21 21:55:00

标签: vba excel-vba excel

这是我的宏所做的。它找到一个给出大型excel文件的字符串并转到该列。此时,它找到用户输入的字符串并将所有结果复制到其旁边的列上。我昨天开始学习VBA,所以感谢任何帮助。

这里是错误的地方 While InStr(UCase(Worksheets("Sheet1").Cells(1, j)), UCase("request")) = 0

到目前为止,这是我的完整宏。

    Sub FineMe()

Dim i, j As Long
Dim count, test As Integer

userinput = InputBox("Enter String", Search, "Collect user input")
Cells.Interior.ColorIndex = 28

 While InStr(UCase(Worksheets("Sheet1").Cells(1, j)), UCase("request")) = 0
    j = j + 1

    Wend

EndRow = Worksheets("Sheet1").Cells(Rows.count, j).End(xlUp).Row
count = 1
    For i = 1 To EndRow
        test = InStr(UCase(Cells(i, j)), UCase(userinput))
            If test > 0 Then
            Cells(count, j + 1).Value = Cells(i, j).Value

            count = count + 1

            End If
    Next i

End Sub

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

只需在j = 1之前添加While,因为在声明Dim i, j As Long之后我们j等于0Worksheets("Sheet1").Cells(1, 0)会触发错误(我们没有Cells(1,0)

Sub FineMe()

    Dim i, j As Long
    Dim count, test As Integer

    userinput = InputBox("Enter String", Search, "Collect user input")
    Cells.Interior.ColorIndex = 28

    j = 1
    While InStr(UCase(Worksheets("Sheet1").Cells(1, j)), UCase("request")) = 0
        j = j + 1
    Wend

    EndRow = Worksheets("Sheet1").Cells(Rows.count, j).End(xlUp).Row
    count = 1
    For i = 1 To EndRow
        test = InStr(UCase(Cells(i, j)), UCase(userinput))
            If test > 0 Then
            Cells(count, j + 1).Value = Cells(i, j).Value

            count = count + 1

            End If
    Next i

End Sub

顺便说一句,在行Dim i, j As Long中,只有jLong,但iVariant。您应该使用Dim i As Long, j As Long代替。与Dim count, test As Integer相同的事情 - 你应该声明如下:Dim count As Integer, test As Integer

答案 1 :(得分:0)

我认为Instr(1,你写的是什么。 在VB编辑器中输入clic Instr,然后按F1