Excel VBA: ListRows.Add doesn't like Table Names as variables?

Anonymous
2017-05-11T12:06:20+00:00

I have VBA code in an Excel project as shown below (I've only shown the relevant bits, and the italicised lines can be ignored).  Version A succeeds but version B falls over with an “Add method of ListRows” failure. 

Does this make sense to anyone? Or have I made an error blindingly obvious to everyone else?  Wouldn't be the first time.....

Version A uses literals instead of values held in strTable& strColName

Private Sub New_Item(strTable As String, strItem As String, strColName As String)

Dim ThisCol As Integer

Dim NextRow As Integer

Dim TopRow As Integer

Dim Tbl As ListObject

Dim NewRow As ListRow

Dim SortRange As String

Worksheets("Factors").Activate

Set Tbl = ActiveSheet.ListObjects("tblNames")

Tbl.ListColumns("Firstname").Range.Select

Set NewRow = Tbl.ListRows.Add(alwaysinsert:=True) 'Add a new row

Version B uses the parameter values

Private Sub New_Item(strTable As String, strItem As String, strColName As String)

Dim ThisCol As Integer

Dim NextRow As Integer

Dim TopRow As Integer

Dim Tbl As ListObject

Dim NewRow As ListRow

Worksheets("Factors").Activate

Set Tbl = ActiveSheet.ListObjects(strTable)

Tbl.ListColumns(strColName).Range.Select

Set NewRow = Tbl.ListRows.Add(alwaysinsert:=True)

The calling sub has this:

If NewItem Then Call New_Item("tblNames", ComboBox1.Value, "Firstname")

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments
{count} votes

14 answers

Sort by: Most helpful
  1. Anonymous
    2017-05-11T15:25:11+00:00

    First of all, there is no need to use the Activate method in VBA, nor the Select. While you can, it certainly isn't necessary.

    I could guess the ActiveSheet, at run-time, isn't the one which houses the Table by your variable name? If it does, it could be that a row either can't be inserted (no row could be consumed), or the sheet was protected. Your code, as posted, works for me.

    Private Sub New_Item( _

            ByVal strTable As String, _

            ByVal strItem As String, _

            ByVal strColName As String _

            )

        Dim ThisCol As Integer

        Dim NextRow As Integer

        Dim TopRow As Integer

        Dim Tbl As ListObject

        Dim NewRow As ListRow

        Set Tbl = Worksheets("Factors").ListObjects(strTable)

        Set NewRow = Tbl.ListRows.Add(AlwaysInsert:=True)

    It will be hard to diagnose without more information, but my best guess is Excel can't insert a row. Perhaps there is something blocking the Table from expanding, most likely data below it, or a merge area which spans past the bounds of the Table [columns].

    There are several issues with a Table which could go wrong when inserting row(s). On top of that, native functionality only allows for a single row insertion, and it always goes at the end. This led me to write my own function to insert rows, but also because I wanted to do more than a single row as well as specify the position. Here is what I use.

    Function InsertRows( _

        ByVal Table As ListObject, _

             Optional ByVal Position As Long, _

             Optional ByVal RowCount As Long = 1, _

             Optional ByVal MessageOnError As Boolean = False _

             ) As Long

    '

    ' Insert a specified number of blank rows into the Table in a given position.

    '

        Dim InsertRange As Range

        Dim HeadersVisible As Boolean

        If Table Is Nothing Then Exit Function

        If RowCount < 1 Then Exit Function

        If Position < 0 Then Exit Function

        HeadersVisible = Table.ShowHeaders

        ' Show headers

        On Error Resume Next

        If HeadersVisible = False Then Table.ShowHeaders = True

        On Error GoTo 0

        If Table.ShowHeaders = False And HeadersVisible = False Then

            If MessageOnError Then MsgBox "Something went wrong. The Table sheet might be protected or the Table can't be shifted.", vbExclamation, "Whoops!"

            Exit Function

        End If

        ' Take care of a simple, single row insert

        If (RowCount = 1 And Position = 0) Or Table.DataBodyRange Is Nothing Then

            Table.ListRows.Add

            If RowCount = 1 And Position = 0 Then Exit Function

        End If

        ' Normalize insert row position

        If Position = 0 Then Position = Table.ListRows.Count + 1

        ' Find range to insert rows

        On Error Resume Next

        If Table.DataBodyRange Is Nothing Then

            Set InsertRange = Table.InsertRowRange.Resize(RowCount)

        Else

            Set InsertRange = Table.DataBodyRange.Resize(RowCount).Offset(Position - 1)

        End If

        On Error GoTo 0

        If InsertRange Is Nothing Then

            If MessageOnError Then MsgBox "Something went wrong. Position could not be found.", vbExclamation, "Whoops!"

            Exit Function

        End If

        ' Perform insert

        On Error Resume Next

        If Intersect(InsertRange.EntireRow, Table.Range) Is Nothing Then

            Table.Resize Table.Parent.Range(Table.Range.Address).Resize(Table.Range.Rows.Count + RowCount, Table.ListColumns.Count)

        Else

            InsertRange.Insert Shift:=xlDown

        End If

        On Error GoTo 0

        If InsertRange Is Nothing Then

            If MessageOnError Then MsgBox "Something went wrong. Rows could not be inserted.", vbExclamation, "Whoops!"

            Exit Function

        End If

        ' Set header visibility to what it was

        If Not HeadersVisible Then Table.ShowHeaders = HeadersVisible

        InsertRows = 1

    End Function

    0 comments No comments
  2. Anonymous
    2017-05-12T02:15:47+00:00

    But why would the two pieces of code not do exactly the same thing? It's more a  question about syntax in VBA. The first code example using literals should do exactly the same thing as the second example using the parameter values.

    alancsears - Did you copy the code from your workbook and paste it here or did you re-type it? Also did you modify what you posted in any way?

    0 comments No comments
  3. Anonymous
    2017-05-13T11:43:38+00:00

    To Zack & D0gknees

    0 comments No comments
  4. Anonymous
    2017-05-13T16:43:00+00:00

    I can't reproduce the problem, and you posted your code in a picture as opposed to text, so I can't copy it to test. Could you possibly upload your test file to the cloud somewhere so we can download it? I work with tables quite a lot (even wrote a book on it), so I'm genuinely interested in finding the problem.

    0 comments No comments
  5. Anonymous
    2017-05-13T18:54:33+00:00

    Zack, I will upload the file as you suggest, when I'm back at my PC.  In the meantime, since I'm a newcomer to Excel tables and I haven't touched VBA since I retired over fifteen years ago, it seemed sensible to buy your book, so I just did.

    Cheers

     Alan

    0 comments No comments