0

I want to Search Data in my Excel Workbook

This code:

Private Sub search_Click()
    Dim totRows As Long, i As Long

    totRows = Worksheets("Sheet4").Range("A1").CurrentRegion.Rows.Count

    If kodebus.Text = "" Then
        MsgBox "Enter the code you wish to search!"
    End If

    For i = 2 To totRows
        If Trim(Sheet4.Cells(i, 1)) <> Trim(kodebus.Text) And i = totRows Then
            MsgBox "Code not found!"
        End If
        If Trim(Sheet4.Cells(i, 1)) = Trim(kodebus.Text) Then
            kodebus.Text = Sheet4.Cells(i, 1)
            namabus.Text = Sheet4.Cells(i, 2)
            jurusanbus.Text = Sheet4.Cells(i, 3)
            hargabus.Text = Sheet4.Cells(i, 4)
            Exit For
        End If
    Next i
End Sub

Finally I get an Error, this message is "Subscript Out Of Range".
And get the position an Error in the code:

totRows = Worksheets("Sheet4").Range("A1").CurrentRegion.Rows.Count

Please help ve to solve it, thanks

GSerg
  • 76,472
  • 17
  • 159
  • 346
  • 1
    So you do not have a sheet named `Sheet4`. You (probably) do have sheet with a [`CodeName`](https://stackoverflow.com/a/33486349/11683) of `Sheet4`, but you do not have a sheet with a `Name` of `"Sheet4"`. – GSerg Jul 28 '19 at 14:06
  • Use `Sheet4.Range("A1").CurrentRegion.Rows.Count` – Mikku Jul 28 '19 at 15:49
  • or you have multiple workbooks open and the wrong workbook is active. If you are sure that your workbook has `sheet4` and the code is in that workbook then try this `totRows = ThisWorkbook.Worksheets("Sheet4").Range("A1").CurrentRegion.Rows.Count` or fully qualify it with the relevant workbook. One more possibilitiy is (i.e if you can see "Sheet") is that the worksheet name has leading or trailing spaces. – Siddharth Rout Jul 28 '19 at 15:51
  • Thank you All, for answer my question... solved it, – Bambang Tri Novianto Jul 30 '19 at 14:13

0 Answers0