Comment vérifier si une cellule commence ou se termine par un caractère spécifique dans Excel ?

Excel: Check Start/End Characters

17/03/2012

Rating: 4.68 (1825 votes)

In the realm of spreadsheet management, accurately identifying and manipulating data based on specific criteria is paramount. Often, you'll find yourself needing to verify if entries within your Excel worksheet begin or conclude with a particular character or string. This could be for anything from validating product codes starting with a specific prefix, to ensuring email addresses adhere to a certain domain ending, or simply cleaning up inconsistent data entries. Excel offers a robust suite of tools to tackle this, from straightforward formulas to more advanced VBA macros and specialised add-ins. This guide will walk you through the most effective methods to confirm if a cell's content starts or ends with your desired character.

Quelle est la différence entre la fonction cherche et la fonction ESTNUM ?
Si c’est le cas, la fonction CHERCHE indiquera une valeur numérique et la fonction ESTNUM renverra VRAI. La fonction SI permet d’effectuer un test logique et de renvoyer une valeur si le test se révèle VRAI et une autre valeur si le test se révèle FAUX.
Table

Checking Cell Start/End Characters with Excel Formulas

Formulas provide a direct and highly adaptable way to perform these checks. They're excellent for creating flags or indicators within your data, allowing for immediate visual cues or further analysis through sorting and filtering. The key functions we'll employ are LEFT, RIGHT, TRIM, and IF.

Verifying the Starting Character

To check if a cell's content begins with a specific character, the LEFT function is your primary tool. It extracts a specified number of characters from the beginning of a text string.

Let's say your data is in column A, starting from cell A2, and you want to check if it starts with the letter 'S'. You can use the following formula in an adjacent cell (e.g., B2):

=IF(LEFT(TRIM(A2),1)='s','OK','Not OK') 

Explanation:

  • TRIM(A2): This function removes any leading or trailing spaces from the cell A2. This is crucial for accurate checks, as an unintended space at the beginning could cause the formula to return 'Not OK'.
  • LEFT(TRIM(A2),1): This extracts the first character from the trimmed text in A2.
  • = 's': This compares the extracted first character to 's'.
  • IF(..., 'OK', 'Not OK'): The IF function returns 'OK' if the first character matches 's', and 'Not OK' otherwise.

To apply this to your entire list, simply drag the fill handle (the small square at the bottom-right of the selected cell) down.

Verifying the Ending Character

Similarly, to check the last character, we use the RIGHT function. It extracts a specified number of characters from the end of a text string.

To check if a cell ends with the character 'n', use this formula in B2:

=IF(RIGHT(TRIM(A2),1)='n','OK','Not OK') 

Explanation:

  • RIGHT(TRIM(A2),1): This extracts the last character from the trimmed text in A2.
  • The rest of the logic is the same as the 'starts with' formula.

Tips for Formula-Based Checks:

  • Case Sensitivity: The formulas above are case-sensitive. If you need a case-insensitive check, convert both the extracted character and the target character to the same case using LOWER() or UPPER(). For example: =IF(LOWER(LEFT(TRIM(A2),1))=LOWER('s'),'OK','Not OK').
  • Multiple Characters: If you need to check for a specific sequence of characters at the beginning or end, you might use the LEFT or RIGHT functions with a higher number, or combine them with functions like SEARCH or FIND for more complex pattern matching.
  • Wildcards: For more flexible pattern matching within formulas (though not directly with LEFT/RIGHT for start/end checks in this simple manner), functions like SEARCH and FIND support wildcards like `?` (single character) and `*` (multiple characters).

Highlighting Cells with Conditional Formatting

Conditional Formatting offers a dynamic visual approach. Instead of adding a new column of 'OK'/'Not OK' indicators, you can directly highlight cells that meet your criteria.

Quel est le synonyme de finissant par elle ?
Voici les mots finissant par ELLE les plus fréquents en français : elle, nouvelle, celle, laquelle, chapelle, actuelle, officielle, appelle. Triés par : Ordre alphabétique Mots fréquents Taille Il y a 2261 mots qui finissent par ELLE. Cliquez sur un mot finissant par ELLE pour voir sa définition.

Steps to Highlight Cells Starting with a Character

  1. Select the range of cells you want to format (e.g., A2:A100).
  2. Go to the Home tab, click Conditional Formatting, then New Rule.
  3. Choose Use a formula to determine which cells to format.
  4. In the formula box, enter:
    =LEFT(TRIM(A2),1)='s' 

    (Replace 's' with your desired character and A2 with the first cell in your selected range).

  5. Click the Format button, choose your desired fill colour or font style, and click OK.
  6. Click OK again to apply the rule.

Steps to Highlight Cells Ending with a Character

  1. Follow steps 1-3 above.
  2. Enter the formula:
    =RIGHT(TRIM(A2),1)='n' 

    (Replace 'n' with your desired character and A2 with the first cell in your selected range).

  3. Click Format, choose your formatting, and click OK twice.

Important Considerations for Conditional Formatting:

  • Relative References: Ensure the cell reference in your formula (e.g., `A2`) is the first cell of your selected range, and that it's a relative reference (no dollar signs unless intended) so it adjusts correctly for each cell in the range.
  • Managing Rules: You can manage multiple rules via Conditional Formatting > Manage Rules. Here you can edit, delete, or change the order of precedence for rules if they conflict.
  • Clearing Formatting: To remove the highlighting, select the cells, go to Conditional Formatting > Clear Rules > Clear Rules from Selected Cells (or the entire sheet).

Using Kutools for Excel: A Powerful Add-in

For users who prefer a more guided, point-and-click approach or need to perform batch operations, add-ins like Kutools for Excel can be invaluable. Kutools offers a suite of over 300 advanced features, including specialised tools for selecting and manipulating cells based on various criteria.

Selecting Cells by Start/End Character with Kutools

  1. Select the data range you want to analyse.
  2. Navigate to the Kutools tab.
  3. Click on Select > Select Specific Cells.
  4. In the dialog box:
    • Under Type of selection, choose Cell.
    • Under Specific type, select either Starts with or Ends with.
    • Enter the character you wish to search for in the adjacent text box.
    • You can also specify multiple criteria if needed.
  5. Click OK. Kutools will instantly select all cells within your range that match your criteria.

This method is particularly effective for quickly isolating data for further actions like copying, deleting, or applying specific formatting, without needing to construct complex formulas.

Automating with VBA Macros

For those who work with large datasets or require a highly repeatable and customisable solution, Visual Basic for Applications (VBA) macros are the way to go.

VBA to Add a Status Column

This macro prompts you to select a range and a character, then outputs 'OK' or 'Not OK' in the column immediately to the right of your selection.

Sub CheckCellStartCharacter() Dim WorkRng As Range Dim CheckChar As String Dim i As Long Dim OutCol As Integer On Error Resume Next Set WorkRng = Application.InputBox("Select the range to check", "KutoolsforExcel", Type:=8) CheckChar = InputBox("Enter the starting character to check (case-sensitive):", "KutoolsforExcel") If WorkRng Is Nothing Or CheckChar = "" Then Exit Sub End If OutCol = WorkRng.Columns(WorkRng.Columns.Count).Column + 1 For i = 1 To WorkRng.Rows.Count If Left(Trim(WorkRng.Cells(i, 1).Value), 1) = CheckChar Then WorkRng.Cells(i, 1).Offset(0, WorkRng.Columns.Count).Value = "OK" Else WorkRng.Cells(i, 1).Offset(0, WorkRng.Columns.Count).Value = "Not OK" End If Next i MsgBox "Check complete. Results output in column " & Chr(65 + WorkRng.Columns.Count), vbInformation End Sub 

VBA to Highlight Cells

This macro highlights cells ending with a specific character in yellow.

Sub HighlightCellsEndingWithChar() Dim WorkRng As Range Dim CheckChar As String Dim i As Long On Error Resume Next xTitleId = "KutoolsforExcel" Set WorkRng = Application.InputBox("Select range to highlight", xTitleId, Type:=8) CheckChar = InputBox("Enter the ending character to highlight (case-sensitive):", xTitleId) If WorkRng Is Nothing Or CheckChar = "" Then Exit Sub End If For i = 1 To WorkRng.Rows.Count If Right(Trim(WorkRng.Cells(i, 1).Value), 1) = CheckChar Then WorkRng.Cells(i, 1).Interior.Color = vbYellow End If Next i MsgBox "Highlighting complete.", vbInformation End Sub 

How to Use VBA Macros:

  1. Press Alt + F11 to open the VBA editor.
  2. Go to Insert > Module.
  3. Paste the chosen code into the module.
  4. Close the editor and return to Excel.
  5. Press F5 or go to the Developer tab > Macros, select the macro name, and click Run.
  6. Follow the prompts to select your range and enter the character.

Frequently Asked Questions (FAQs)

Q1: Can I check for multiple starting characters (e.g., 'S' or 'T') with a single formula?

A1: Yes, you can nest IF statements or use the OR function. For example: =IF(OR(LEFT(TRIM(A2),1)='s', LEFT(TRIM(A2),1)='t'),'OK','Not OK').

Combien de mots de 5 lettres finissent par IN en français?
Il y a 325 mots de 5 lettres qui finissent par IN en français. Voici la liste de tous les mots français de 5 lettres finissant par IN groupés par nombre de lettres : accin, admin, affin, Afrin, Agnin, Ajain, Alain, Albin, aldin, Allín, alpin. Cliquez sur un mot de 5 lettres finissant par IN pour voir sa définition. …

Q2: How do I make the check case-insensitive?

A2: Use the LOWER() or UPPER() function on both the cell content and your target character. For instance: =IF(LOWER(LEFT(TRIM(A2),1)) = LOWER('s'), 'OK', 'Not OK').

Q3: What's the difference between SEARCH and FIND?

A3:FIND is case-sensitive and does not support wildcards. SEARCH is not case-sensitive and supports wildcards (`?` and `*`). For checking the very first or last character specifically, LEFT and RIGHT are generally more direct than SEARCH or FIND, though the latter are powerful for finding characters anywhere within a string.

Q4: Does conditional formatting update automatically?

A4: Yes, conditional formatting is dynamic. If you change the data in a cell or add new rows, the formatting will automatically update based on the rules you've set, provided the rules are correctly applied to the relevant range.

Q5: Is Kutools a free add-in?

A5: Kutools for Excel is a commercial add-in, but it typically offers a free trial period, allowing you to test its extensive features before purchasing a license.

Conclusion

Mastering the ability to check if cells start or end with specific characters in Excel is a fundamental skill for efficient data management. Whether you opt for the simplicity of formulas, the visual clarity of conditional formatting, the power of add-ins like Kutools, or the automation capabilities of VBA, Excel provides versatile solutions to suit every need. By applying these techniques, you can significantly enhance your data accuracy, streamline your analysis, and improve your overall productivity within Excel.

If you want to read more articles similar to Excel: Check Start/End Characters, you can visit the Automotive category.

Go up