Excelinput框VBA错误检查问题
以下是我更改的代码。 我无法弄清楚VBA的生活。 如果这是c ++,那我需要30秒才能写出来。 我仍然得到错误。
Sub CodeFinder() Dim userInput As String Dim errorCheck As String userInput = InputBox("Please enter the code to search", "Code Search Engine") errorCheck = Cells.Find(What:=userInput, _ After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False) If errorCheck = False Then MsgBox ("Error") Else Cells.Find(What:=userInput, _ After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False).Activate End If End Sub
如果Cells.Find
失败,则返回Nothing
。 所以你需要把它分配给一个variables,并在尝试之前检查它的值。 .Activate
它。
实际上你也应该检查InputBox
的返回值,如果点击Cancel。
编辑:仍然包含一些错误。
-
Cells.Find
返回一个Range
,但是你试图把它分配给一个String
variables。 (另外不要忘记,Range
和String
variables有不同的赋值语句。) - 然后尝试将该variables与
False
进行比较,而不是检查它是否为Nothing
。 - 然后您需要激活find的
Range
而不是试图再次find它。
Sub CodeFinder() Dim userInput As String Dim rFound As Range userInput = InputBox("Please enter the code to search", "Code Search Engine") If Len(userInput) > 0 Then Set rFound = ActiveSheet.Cells.Find(What:=userInput, _ After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False) If Not rFound Is Nothing Then rFound.Select Else MsgBox "No cells found" End If End If End Sub