2017-10-04 104 views
0

類似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

回答

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 

我想你會得到你想要的東西。

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 

此取景宏還去了發現價值,像你說你想要的,並突出顯示它。

的代碼是開源的,公共領域,可以隨意使用和/或改變它。

+0

非常感謝你,你的代碼很棒。它不是通過公式,我只是意識到,試圖找到代碼的價值是從不同的工作表參考,所以他們是公式。不幸的是,我不能只複製和粘貼到值,他們必須保持公式。你知道是否有什麼我可以添加到你的代碼,使它看起來雖然公式? –

+1

@ S.MART你是否試圖搜索公式中的文本(即'LookIn:= xlFormulas'),或搜索值中的文本由這些公式計算(即'LookIn:= xlValues')?例如如果你在Excel中有'=「ab」&「cd」'的公式,那麼在'xlFormulas'中搜索''abcd「'會失敗,但是在'xlValues'中搜索它會找到它。 – YowE3K