如果在搜索excel时未找到值

时间:2015-06-16 21:42:03

标签: vb.net

我有以下代码:

        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()

以上工作正常。但我想添加一种方法,如果找不到你正在搜索的值。我试过添加一个' else'到了'如果'声明,但只是它每次都给出错误。

1 个答案:

答案 0 :(得分:2)

您需要另一个变量来跟踪是否找到它:

    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