通过确认查找并突出显示macros

我有这个macros下面的工程很好find一个数字,并确认是否正确(然后突出显示)。 首先它询问您寻找的号码,然后input号码,然后点击确定。 然后,如果它find了号码,那么你将有机会说是否或取消(以防万一他们是多个号码,你正在寻找,而不是正确的)。 如果你点击是,它会突出显示该单元格。

问题:

  1. 如果您正在查找的号码不在表单上,​​macros将出错。
  2. 如果你打“不”,我希望它寻找下一个号码,如果他们没有下一个号码,那么就退出。 (这个button也可以被称为“下一步”,因为它可以更准确地描述情况。

任何帮助将不胜感激! 谢谢!

Sub find_highlight() Dim w As Variant Dim FoundCell As Range Dim ans As String Do w = InputBox("What to find?") Cells.Find(What:=(w), After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False).Activate Select Case MsgBox("Is this the number?", vbYesNoCancel) Case vbNo Case vbYes With Selection.Interior .ColorIndex = 6 .Pattern = xlSolid .PatternColorIndex = xlAutomatic End With Case vbCancel Exit Do End Select Loop End Sub 

你真的应该分成多个职位。 每个post有一个问题,请。

至于你看到的错误:你必须检查错误情况。

 Sub find_highlight() Dim w As Variant Dim FoundCell As Range Dim ans As String Do w = InputBox("What to find?") On Error Resume Next thisRng1 = ActiveCell.Address Cells.Find(What:=(w), After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False).Activate thisRng2 = ActiveCell.Address If thisRng1 = thisRng2 Then MsgBox "Value Not Found" End If On Error GoTo 0 Select Case MsgBox("Is this the number?", vbYesNoCancel) Case vbNo Case vbYes With Selection.Interior .ColorIndex = 6 .Pattern = xlSolid .PatternColorIndex = xlAutomatic End With Case vbCancel Exit Do End Select Loop End Sub 

以下代码:

  • 允许用户通过简单的不给一个值来search而退出程序
  • 看起来在“价值”而不是“公式”(仅仅是因为我怀疑你想search公式的结果,而不是公式的结果本身 – 即如果你有一个公式=5+4你会想要匹配它如果用户正在search9 ,而不是他们正在search4
  • 避免出现错误,当您尝试Activate发生匹配的单元格时,如果没有发生匹配,则通过不尝试Activate直到已经执行testing以确保发生匹配
  • 如果用户经常说“否”,返回到第一个匹配,则退出search

 Sub find_highlight() Dim w As Variant Dim FoundCell As Range Dim FirstMatch As String Dim ans As String Do w = InputBox("What to find?") If w = "" Then 'Exit the procedure if the user gave us nothing to look for Exit Sub End If 'Don't activate the cell straight away 'Search in values instead of in formulas Set FoundCell = Cells.Find(What:=w, After:=ActiveCell, LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False) 'Check to see if we found a match If Not FoundCell Is Nothing Then 'Store where the first match was found FirstMatch = FoundCell.Address Do Application.GoTo FoundCell 'safer than FoundCell.Activate Select Case MsgBox("Is this the number?", vbYesNoCancel) Case vbNo Case vbYes With FoundCell.Interior .ColorIndex = 6 .Pattern = xlSolid .PatternColorIndex = xlAutomatic End With 'Found and processed, quit looking for this particular value Exit Do Case vbCancel 'Quit the entire procedure - user doesn't want to search any more Exit Sub End Select 'Find the next match Set FoundCell = Cells.FindNext() 'If back at the first match, quit this loop If FoundCell.Address = FirstMatch Then Exit Do End If Loop End If Loop End Sub