Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a row from Excel table using VBA

Within Excel, I use tables to store dynamic data inside a seperate worksheet. Entering new data works like a charm, however, I would like to be able to dynamically retrieve a single row from that table and store its data in variables. I would prefer to build a function so I could do something like this:

findFromCatsByDate(searchterm) 'returns a single row if found with mathing date.

Note that the table is dynamic and not a fixed range (so it changes vertically). I want to reuse this function with slight modification on other tables. I kind of need an example how to achieve this in VBA.

Thanks,

like image 281
Shyam Avatar asked Jan 19 '23 14:01

Shyam


1 Answers

This will return a reference the row that matches Key in a specified table

Function GetRow(TableName As String, ColumnNum As Long, Key As Variant) As Range
    On Error Resume Next
    Set GetRow = Range(TableName) _
        .Rows(WorksheetFunction.Match(Key, Range(TableName).Columns(ColumnNum), 0))
    If Err.Number <> 0 Then
        Err.Clear
        Set GetRow = Nothing
    End If
End Function

Example use

Sub zx()
    Dim r As Range
    Set r = GetRow("MyTable", 1, 2)
    If Not r Is Nothing Then
        r.Select
    End If
End Sub
like image 171
chris neilsen Avatar answered Jan 24 '23 20:01

chris neilsen