ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

VBA: Find First Matching Cell in Range

VBA (Visual Basic for Applications)

Goal -- WPM

Ready
Exercise Algorithm Area
1Function FindFirstMatch(targetValue As Variant, searchRange As Range) As Range
2' Finds the first cell in searchRange that matches targetValue.
3' Returns Nothing if no match is found or if the range is invalid.
4
5Dim foundCell As Range
6
7' Basic validation for the input range
8If searchRange Is Nothing Then
9Set FindFirstMatch = Nothing
10Exit Function
11End If
12
13On Error Resume Next ' Handle potential errors with range properties
14If searchRange.Cells.Count = 0 Then
15Set FindFirstMatch = Nothing
16On Error GoTo 0
17Exit Function
18End If
19On Error GoTo 0
20
21' Use the Find method for efficiency
22Set foundCell = searchRange.Find(What:=targetValue, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
23
24' Check if a match was found
25If Not foundCell Is Nothing Then
26Set FindFirstMatch = foundCell
27Else
28Set FindFirstMatch = Nothing
29End If
30
31End Function
Algorithm description viewbox

VBA: Find First Matching Cell in Range

Algorithm description:

This VBA function efficiently searches for the first occurrence of a specified value within a given Excel range. It utilizes the built-in `Find` method, which is optimized for this task. This is commonly used in data processing macros to locate specific entries for further manipulation or reporting.

Algorithm explanation:

The `FindFirstMatch` function takes a `targetValue` and a `searchRange` as input. It first performs basic validation to ensure the `searchRange` is not `Nothing` and contains at least one cell. It then employs the `Range.Find` method, a highly optimized Excel feature, to locate the first cell matching `targetValue`. The `LookIn`, `LookAt`, and `MatchCase` arguments are set for a typical whole-cell, case-insensitive search. If `Find` returns a `Range` object (meaning a match was found), that object is assigned to the function's return value. Otherwise, `Nothing` is returned. This approach is efficient because `Range.Find` is implemented at a lower level within Excel. The primary edge cases handled are an invalid or empty input range and the scenario where the target value is not present in the range.

Pseudocode:

FUNCTION FindFirstMatch(targetValue, searchRange)
  IF searchRange is invalid OR empty THEN
    RETURN Nothing
  END IF

  SET foundCell = searchRange.Find(targetValue)

  IF foundCell is not Nothing THEN
    RETURN foundCell
  ELSE
    RETURN Nothing
  END IF
END FUNCTION