Application of vba on the Find method (Find method) (1)

[VBA] on the application of the Find method (Find method) (1)
fanjy published on 2006-9-28 20:14:00 excelhome

In Excel, select the menu "Edit" - "Find (F)..." command or press the "Ctrl+F" key combination, the "Find and Replace" dialog box will pop up as shown in Figure 01 below. In the "Find" tab, enter the content to be searched and set relevant options to search, and Excel will locate the active cell in the corresponding cell found. If it does not find what you are looking for, Excel will pop up a message box saying "Excel cannot find the data it is searching for".
 
Figure 01: "Find" dialog
This function of Excel is very useful for finding specified data, especially when searching for data in a worksheet containing a large amount of data, it can better reflect the speed and convenience of this function. Likewise, using the Find method corresponding to this function in ExcelVBA provides an easy way to find specific data in a range of cells and is faster than the traditional loop method.


1. The function of the
Find method The Find method will search for the cell containing the data specified by the parameter in the specified cell range. If the data that meets the conditions is found, it will return the cell containing the data; if no matching data is found, then Returns Nothing. This method returns a Range object, which, when used, does not affect the selection or the active cell.


2. Syntax of the Find method
[Syntax]
< Cell Range >.Find (What, [After], [LookIn], [LookAt], [SearchOrder], [SearchDirection], [MatchCase], [MatchByte], [SearchFormat] )
[parameter description]
(1) <cell range>, which must be specified, returns a Range object.
(2) The parameter What, must be specified. Represents the data to be searched, which can be a string, an integer, or any other data type. Corresponds to the contents of the Find what text box in the Find and Replace dialog box.
(3) Parameter After, optional. Specify the position to start the search, that is, start the search backward or before the cell where the position is located (that is, the cell where the position is located is not searched at the beginning until the Find method wraps around to the cell, search for its content). The specified position must be a single cell in the cell range. If this parameter is not specified, the search will start after the cell in the upper left corner of the cell range.
(4) Parameter LookIn, optional. Specifies the search range type, which can be one of the following constants: xlValues, xlFormulas or xlComments, the default value is xlFormulas. Corresponds to the options in the Find in drop-down box in the Find and Replace dialog box.
(5) Parameter LookAt, optional. Can be one of the following constants: XlWhole or xlPart, used to specify whether the searched data matches the cell content completely or partially, the default value is xlPart. Corresponds to the Match Cells check box in the Find and Replace dialog box.
(6) Parameter SearchOrder, optional. Used to determine how to search in the cell range, whether to search in rows (xlByRows) or columns (xlByColumns). The default value is xlByRows. Corresponds to the options in the Search drop-down box in the Find and Replace dialog box.
(7) Parameter SearchDirection, optional. It is used to determine the search direction, that is, whether to search forward (XlPrevious) or backward (xlNext). The default is to search backward.
(8) Parameter MatchCase, optional. If the value of this parameter is True, the search is case sensitive. The default value is False. Corresponds to the Case Sensitive check box in the Find and Replace dialog box.
(9) Parameter MatchByter, optional. That is, whether to distinguish between full-width and half-width, it is used when a double-byte language is selected or installed. If this parameter is True, double-byte characters are matched only with double-byte characters; if this parameter is False, double-byte characters are matched with their identical single-byte characters. Corresponds to the "Distinguish full/half width" check box in the "Find and Replace" dialog box.
(10) The parameter SearchFormat, optional, specifies an exact type of search format. Corresponds to the Format button in the Find and Replace dialog box. When setting up a lookup with the corresponding format, the value of this parameter is True.
(11) After each use of the Find method, the settings of the parameters LookIn, LookAt, SearchOrder, and MatchByte will be saved. If the value of these parameters is not changed or specified the next time this method is used, the method will use the saved value.
Setting these parameters in VBA will change the settings in the Find and Replace dialog; similarly, changing the settings in the Find and Replace dialog will also change the saved values. That is to say, after writing a piece of code, if the above parameters are not specified in the code, it may meet the requirements in the initial run, but if the user changes these parameters in the "Find and Replace" dialog box, they will be reflected at the same time. into the program code, when the code is run again, the result may be different or wrong. To avoid this problem, it is recommended to explicitly set these parameters each time you use it.
3. Find method using example
3.1 This example finds the cell with the value represented by the what variable in the active worksheet, and deletes the column in which the cell is located.
'- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sub Find_Error()
  Dim rng As Range
  Dim what As String
  what = " Error"
  Do
    Set rng = ActiveSheet.UsedRange.Find(what)
    If rng Is Nothing Then
      Exit Do
    Else
       Columns(rng.Column).Delete
    End If
  Loop
End Sub
'- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3.2 Formatted Find
This example finds cells in the current worksheet cell with the font "Arial Unicode MS" and the color red. Among them, the Application.FindFormat object allows to specify the format to be searched. At this time, the parameter SearchFormat of the Find method should be set to True.
'- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sub FindWithFormat()
  With Application.FindFormat.Font
        .Name = "Arial Unicode MS"
        .ColorIndex = 3
  End With
  Cells.Find(what:="", SearchFormat:=True).Activate
End Sub
'- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[Summary] After using the Find method to find the data that meets the conditions, you can perform corresponding operations on it. You can:
(1) Operate the cell where the data is located;
(2) Operate the row or column of the cell where the data is located;
(3) Operate the cell range where the data is located.


4. The method associated with the Find method
can use the FindNext method and the FindPrevious method for repeated searches. Before using these two methods, the Find method must be used to specify the data content to be searched.
4.1 FindNext method
The FindNext method corresponds to the "Find Next" button in the "Find and Replace" dialog box. You can use this method to continue the search, find the next cell that matches the data of the criteria specified in the Find method, and return a Range object representing that cell. When using this method, the selection or the active cell is not affected.
4.1.1 Syntax
< cell range >.FindNext(After)
4.1.2 Parameter description
Parameter After, optional. Represents the specified cell, after which the search will start. The cell where the position is located is not searched at the beginning, and its contents are not searched until the FindNext method wraps back to the cell. The specified position must be a single cell in the cell range. If this parameter is not specified, the search will start after the cell in the upper left corner of the cell range.
When the end of the specified search area is found, this method will wrap around to the beginning of the area and continue searching. After wrapping occurs, in order to stop the search, you can save the cell address found for the first time, and then test whether the address of the next cell found is the same as the condition for judging the search exit to avoid an infinite loop. Of course, if the cell data found is changed during the search process, this judgment may not be made, as shown in the following example.
4.1.3 Some questions about the VBA help system
In the VBA help system, the example used to introduce the Find method and the FindNext method seems to have a problem: when running in Excel, although the running result is correct, when it runs to the end, it will report an error: Run-time error '91': Object variable or With block variable not set. The reason may be the problem of the object variable c, because when the search is performed and the corresponding values ​​are all changed, the final value of the variable c is Nothing. After changing it a little, it runs through.
The original example code is as follows: (You can also refer to the VBA help system Find method or FindNext method help topic)
This example finds cells with a value of 2 in the cell range A1:A500, and changes the value of these cells to 5.
With Worksheets(1).Range("a1:a500")
  Set c = .Find(2, lookin:=xlValues)
  If Not c Is Nothing Then
    firstAddress = c.Address
    Do
      c.Value = 5
      Set c = .FindNext( c)
    Loop While Not c Is Nothing And c.Address <> firstAddress
  End If
End With 
The modified sample code is as follows, that is, an error handling statement On Error Resume Next is added to the original code , ignoring the error that occurs.
Sub test1()
  Dim c As Range, firstAddress As String
  On Error Resume Next
  With Worksheets(1).Range("a1:a15")
    Set c = .Find(2, LookIn:=xlValues)
    If Not c Is Nothing Then
      firstAddress = c.Address
      Do
        c.Value = 5
        Set c = .FindNext(c)
      Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
  End With
End Sub  Or, modify the code as follows, that is, remove the condition c.Address <> firstAddress
of the last judgment loop in the original code , because the function of this program is to find a cell with a value of 2 in the specified area and replace it with a value of 5. When the program cannot find the value of 2 in the specified area, it will exit the loop, which does not involve the problem of repeated loops. Sub test2()   Dim c As Range, firstAddress As String   With Worksheets(1).Range("a1:a15")     Set c = .Find(2, LookIn:=xlValues)     If Not c Is Nothing Then





      firstAddress = c.Address
      Do
        c.Value = 5
        Set c = .FindNext(c)
      Loop While Not c Is Nothing
    End If
  End With
End Sub 
You can also try this program to see if my understanding is correct, or else any other solution.
4.2 FindPrevious method
You can use this method to continue the search performed by the Find method, find the previous cell that matches the data of the condition specified in the Find method, and return the Range object representing the cell. When using this method, the selection or the active cell is not affected.
4.2.1 Syntax
< cell range >.FindPrevious(After)
4.2.2 Parameter description
Parameter After, optional. Represents the specified cell, and the search will start before the cell. The cell at that location is not searched initially, and its contents are not searched until the FindPrevious method wraps around to the cell. The specified location must be a single cell in the cell range, if this parameter is not specified, the search will start before the cell in the upper left corner of the cell range.
When the starting position of the specified search area is found, this method will wrap around to the end of the area to continue searching. After wrapping occurs, in order to stop the search, you can save the cell address found for the first time, and then test whether the address of the next cell found is the same as the condition for judging the search exit to avoid an infinite loop.
4.2.3 Example
Enter the data shown in Figure 02 below in the worksheet, at least ensure that there are two cells in column A with the data "excelhome" entered.
 Figure 02: Tested data
Enter the following code in the VBE editor to test the Find method, FindNext method, and FindPrevious method, and experience the cell location found by each method.
'- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sub testFind()
  Dim findValue As Range
  Set findValue = Worksheets("Sheet1 ").Columns("A").Find(what:="excelhome")
  MsgBox "First data found in cell:" & findValue.Address
  Set findValue = Worksheets("Sheet1").Columns("A" ).FindNext(After:=findValue)
  MsgBox "Next data found in cell:" & findValue.Address
  Set findValue = Worksheets("Sheet1").Columns("A").FindPrevious(After:=findValue)
  MsgBox " The previous data was found in cell " & findValue.


By fanjy in 2006-9-28

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325267350&siteId=291194637