Cross Referencing Excel Table Objects

38 Views Asked by At

I have a Table Object that needs to be filled with data under certain conditions.

The Condition comes from the "Flag Desc" column in the print below. If this condition is true, it will be put into the "Desc" column in the left table and the "D Out" value in the same line will be put into the "MD" column in the same left table.

enter image description here

I'm completely capable in a normal range, but i do not know how to do it in a table object range. I've looked over many forums and articles trying different combinations of codes but without success.

I'm stuck at the point where i cannot refer the same row in the "Flag Desc" column with "D Out" column to get its value.

Can someone shed a light?

Cheers,

1

There are 1 best solutions below

0
z32a7ul On

There is nothing special about ListObjects (aka Tables), you can enter values after their last row, and they will grow automatically. You can write something along these lines:

Option Explicit

Public Sub InsertIntoTable()
    Dim rng As Range: Set rng = ThisWorkbook.Worksheets("Sheet1").Range("H2:K10")
    Dim colDOut As Long: colDOut = 1
    Dim colFlagDesc As Long: colFlagDesc = 4
    Dim tbl As ListObject: Set tbl = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
    Dim colMD As Long: colMD = 1
    Dim colDesc As Long: colDesc = 3
    Dim r As Long: For r = 1 To rng.Rows.Count
        If rng.Cells(r, colFlagDesc).Value <> "" Then
            Dim dst As Range: Set dst = tbl.DataBodyRange.Rows(tbl.DataBodyRange.Rows.Count).Offset(1, 0)
            dst.Cells(1, colMD).Value = rng.Cells(r, colDOut).Value
            dst.Cells(1, colDesc).Value = rng.Cells(r, colFlagDesc).Value
        End If
    Next
End Sub