搜索框/按钮在VBA

问题描述:

类似CTRL + F我试图弄清楚什么是对CTRL +˚F命令的实际代码,但无法找到它。我发现的最近的是粘贴在下面;唯一的问题是我无法正确更改范围。搜索框/按钮在VBA

我想改变范围来查找整个工作表中的值只在A列。我还想,如果不是返回一条消息说它找到了X行的值,我更喜欢它是否真的去它。我是VBA的新手,我对理解活动范围的理解最为困难。

Sub PlayMacro() 

    Dim Prompt As String 
    Dim RetValue As String 
    Dim Rng As Range 
    Dim RowCrnt As Long 

    Prompt = "" 

    ' The macro recorder has used the active worksheet. This says which 
    ' worksheet is to be used whether it is active or not. Change "Sheet4" 
    ' to the name of your worksheet. 
    With Sheets("Sheet4") 

    ' This will loop forever unless a statement within 
    ' the loop exits the Do. 
    Do While True 

     RetValue = InputBox(Prompt & "Give me a value to look for") 
     'RetValue will be empty if you click cancel 
     If RetValue = "" Then 
     Exit Do 
     End If 

     ' I do not wish to active the cell containing the required value. 
     ' I want to know where it is. 
     Set Rng = .Columns("A:A").Find(What:=RetValue, After:=.Range("A1"), _ 
       LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _ 
       SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) 

     If Rng Is Nothing Then 
     ' The entered value could not be found 
     Prompt = "I could not find """ & RetValue & """" 
     Else 
     ' The entered value was found 
     RowCrnt = Rng.Row 
     Prompt = "I found """ & RetValue & """ on row " & RowCrnt 
     End If 
     Prompt = Prompt & vbLf 
    Loop 

    End With 
+0

什么是你的代码错误?它只搜索A列。如果找到'Rng',那么您可以执行'Rng.select'来激活找到该值的单元格。你也可以这样说'If Rng.Row = 3 Then ...'如果值在第三行...?如果你想搜索整个表格,只要执行'Set Rng = .Cells.Find(...' – BruceWayne

+4

FWIW'LookIn:= xlFormulas,LookAt:= xlWhole'是一个奇怪的组合,特别是当用户提示是“给我一个**值**寻找” - 你确定你不想看“xlValues”吗? – YowE3K

如果你改变你的代码的最后一部分:

If Rng Is Nothing Then 
    ' The entered value could not be found 
    Prompt = "I could not find """ & RetValue & """" & vbLf 
    Else 
    ' The entered value was found 
    Application.GoTo Rng 
    Prompt = "" 
    End If 
Loop 

我想你会得到你想要的东西。

excel-finder-macro(GitHub上)是一个Excel宏我做了一段时间后,你可以玩弄和更改范围。

因为它只是一个VBA宏,你可以定制你想要的东西,包括限制搜索仅列A自述:

宏目前搜索的范围内的所有单元格距离最远在列A中具有值的行,一直到列ZZ。可以通过更改cellRange变量来进一步搜索,或基于不同的列搜索行。该宏不区分大小写,并会在其他文本中查找字符或部分字符串。

cellRange是默认设置为:

numRows = ActiveSheet.Range("A1048576").End(xlUp).Row 
cellRange = "a1:zz" & numRows 

您可以用价值发挥和约束他们,你想要的任何方式。例如,仅在A列中进行搜索,你可以改变cellRange到:

cellRange = "a1:a1" & numRows 

此取景宏还去了发现价值,像你说你想要的,并突出显示它。

的代码是开源的,公共领域,可以随意使用和/或改变它。

+0

非常感谢你,你的代码很棒。它不是通过公式,我只是意识到,试图找到代码的价值是从不同的工作表参考,所以他们是公式。不幸的是,我不能只复制和粘贴到值,他们必须保持公式。你知道是否有什么我可以添加到你的代码,使它看起来虽然公式? –

+1

@ S.MART你是否试图搜索公式中的文本(即'LookIn:= xlFormulas'),或搜索值中的文本由这些公式计算(即'LookIn:= xlValues')?例如如果你在Excel中有'=“ab”&“cd”'的公式,那么在'xlFormulas'中搜索''abcd“'会失败,但是在'xlValues'中搜索它会找到它。 – YowE3K