Home » excel » vba – Excel: write entire ListObject Column

vba – Excel: write entire ListObject Column

Posted by: admin May 14, 2020 Leave a comment

Questions:

How can I simply write values from an array to an entire ListObject Column at once (data rows only, excluding header)? I found a solution but I don’t think it’s pretty:

' needs: ActiveSheet with ListObject "Tabelle1",
' with second column heading "Spalte2" and 4 data rows
Sub WriteLoColumnTest()
    Dim lo As ListObject
    Set lo = ActiveSheet.ListObjects("Tabelle1")

    Dim va(1 To 4, 1 To 1) As Variant
    va(1, 1) = "a"
    va(2, 1) = "b"
    va(3, 1) = "c"
    va(4, 1) = "d"

    ' here it comes:
    lo.ListColumns("Spalte2") _
        .Range _
        .Resize(lo.ListRows.Count) _
        .Offset(1) _
        .Value2 = va
End Sub

I need .ListColumns and .Range to get my range and .Resize and .Offset to skip headings row. Is there an easier way?

How to&Answers:

If you’re just looking for a simpler way to do this you can achieve the same using the below

Sub WriteLoColumnTest()
    Dim lo As ListObject: Set lo = ActiveSheet.ListObjects("Tabelle1")
    Dim va As Variant

    va = Array("a", "b", "c", "d")
    lo.ListColumns("Spalte2").DataBodyRange.Value2 = Application.Transpose(va)
End Sub

For further reading you might want to familiarise yourself with the different parts of the listobject

https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables