0

I have the below code:

        Dim xlApp As Excel.Application
        Dim xlBook As Excel.Workbook
        Dim xlSheet1 As Excel.Worksheet
        Dim rng As Excel.Range
        Dim codeabc As String
        Dim i As Integer
        If StoreNumber.Text = String.Empty Then
            MsgBox("Please fill out 'Store Number'")
            Exit Sub
        End If
        xlApp = CreateObject("Excel.Application")
        xlBook = xlApp.Workbooks.Open("C:\Users\jefhill\Desktop\MyUPS.csv")
        xlSheet1 = xlBook.Worksheets(1)
        rng = xlSheet1.Range("a1:a3000")
        codeabc = (StoreNumber.Text)
        For i = 1 To rng.Count
            If rng.Cells(i).Value = codeabc Then
                Address.Text = (rng.Cells(i).offset(0, 1).value()) & vbCrLf & (rng.Cells(i).offset(0, 2).value()) & " " & (rng.Cells(i).offset(0, 3).value()) & " " & (rng.Cells(i).offset(0, 4).value())
                Phone.Text = (rng.Cells(i).offset(0, 5).value())
            End If
        Next i
        xlBook.Close()

The above works fine. But I am trying to add a way where if the value you are searching is NOT found. I have tried adding a 'else' to the 'if' statement, but that just had it give the error every time.

1
  • What error are you getting? Commented Jun 16, 2015 at 21:45

1 Answer 1

2

You need another variable to track if it was found:

    Dim found as Boolean
    found = False
    For i = 1 To rng.Count
        If rng.Cells(i).Value = codeabc Then
            Address.Text = (rng.Cells(i).offset(0, 1).value()) & vbCrLf & (rng.Cells(i).offset(0, 2).value()) & " " & (rng.Cells(i).offset(0, 3).value()) & " " & (rng.Cells(i).offset(0, 4).value())
            Phone.Text = (rng.Cells(i).offset(0, 5).value())

            'set the flag
            found = True
        End If
    Next i

    If Not found Then
        'logic if not found
    End If
Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfect - and you were so quick I cannot even answer question answered yet! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.