Search code examples
vbalistobject

Is there a way in VBA to add a ListRow object and specify the columns by name?


I have a table called "Names" like this

Name Value
Pete 5
Hugo 1

and would like to add new data point, let's say "Malcolm, 9".

I can do it like this:

Sub addName()

Dim tbl as Listobject: Set tbl = Range("Names").ListObject
With tbl.ListRows.Add
    .Range(1) = "Malcolm"
    .Range(2) = 9
End With

End Sub

For the sake of flexibility, changing column order, inserted columns and the like, I would like to do it like this:

Sub addName()

Dim tbl as Listobject: Set tbl = Range("Names").ListObject
With tbl.ListRows.Add
    .Range("Name") = "Malcolm"
    .Range("Value") = 9
End With

End Sub

Is there a way in VBA to achieve this easily? There is a workaround in which you check the table header first, and look for the position of the column name. But that is overly tedious.


Solution

  • Hope this not-so-tedious workaround will do the trick. You need to insert two more lines.

    Sub addName3()
    
    Dim tbl As ListObject
    Dim clm1 As Integer
    Dim clm2 As Integer
    
    Set tbl = Range("Names").ListObject
    
    clm1 = tbl.ListColumns("Name").Index
    clm2 = tbl.ListColumns("Value").Index
    
    
    With tbl.ListRows.Add
        .Range(clm1) = "Malcolm"
        .Range(clm2) = 9
    End With
    
    End Sub