搜索框/按钮类似于VBA中的CTRL + F.

时间:2017-10-04 19:31:25

标签: excel vba excel-vba

我试图弄清楚 CTRL + F 命令的实际代码是什么,但无法找到它。我找到的最接近的是贴在下面;唯一的问题是我无法正确改变范围。

我想更改范围以在整个工作表中仅在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

2 个答案:

答案 0 :(得分:0)

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

此Finder宏也会像您所说的那样找到找到的值,然后突出显示它。

代码是开源和公共域,因此可以随意使用和/或更改它。

答案 1 :(得分:0)

如果您将代码的最后一部分更改为:

  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

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