0

New to VBA. I need to enter a number in text box and search spreadsheet for that number and then return the data in columns beside the found number in text boxes in form. I have done this but the question I have is how to write an exception if the number is not found?

4

2 回答 2

0

You can do this with a formula. Let's assume your number is in A1 and your list of numbers is in column D. You want the text in column E if you find the number in A1 within the list in Column D.

Normally you would just use VLOOKUP().

=VLOOKUP(A1,D:E,2,FALSE)

You can add a simple IF statement and ISERROR() to check if it succeeded in finding the number or not. Normally Excel will return "#N/A" if it was an error, but let's assume you want a message.

=IF(ISERROR(VLOOKUP(A1,D:E,2,FALSE)),"ERROR",VLOOKUP(A1,D:E,2,FALSE))
于 2012-12-13T08:03:30.517 回答
0

像这样。对工作表名称、范围名称、文本框名称等所做的假设。仅出于说明目的而向您展示如何去做

Sub FindNumber()

Dim myNum

myNum = TextBox1.Value

Dim rng as Range

Set rng = Sheets(1).Range("A1:A100").Find(myNum,lookat:xlWhole)

If Not rng is Nothing Then

    '[Rest of Code]

Else

   Msgbox myNum & "not found in Range"

End If

End Sub
于 2012-12-10T19:34:54.443 回答