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。

编辑:仍然包含一些错误。

  1. Cells.Find返回一个Range ,但是你试图把它分配给一个Stringvariables。 (另外不要忘记, RangeStringvariables有不同的赋值语句。)
  2. 然后尝试将该variables与False进行比较,而不是检查它是否为Nothing
  3. 然后您需要激活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