Hi,
I'm trying to have VBA count the number of instances of a string within a table, then save the table row of each instance. I then want to take these saved rows and add their data in new rows in a table elsewhere.
As an example, below are two tables (Let's call them "tblThings" and "tblNew"). tblThings includes two instances of "Thing1." My idea is that VBA finds Thing1 in rows 2 and 4 (including the header row) of the table. Then, using a For loop, a new row is added to tblNew. The data for each respective row is then added.
tblThings
<tbody>
</tbody>
tblNew (I should note other rows besides the new ones already existed, but are not shown here)
<tbody>
</tbody>
I have been able to get the number of rows containing Thing1 using a CountIf line, but that isn't quite what I need. I can't seem to figure out any good way to do this. Thanks for any assistance!
I'm trying to have VBA count the number of instances of a string within a table, then save the table row of each instance. I then want to take these saved rows and add their data in new rows in a table elsewhere.
As an example, below are two tables (Let's call them "tblThings" and "tblNew"). tblThings includes two instances of "Thing1." My idea is that VBA finds Thing1 in rows 2 and 4 (including the header row) of the table. Then, using a For loop, a new row is added to tblNew. The data for each respective row is then added.
tblThings
Name | Data |
Thing1 | 11 |
Thing2 | 33 |
Thing1 | 55 |
Thing3 | 77 |
<tbody>
</tbody>
tblNew (I should note other rows besides the new ones already existed, but are not shown here)
Name | Data |
Thing1 | 11 |
Thing1 | 55 |
<tbody>
</tbody>
Code:
Sub Muffins()
Dim tblThings As Object
Dim tblNew As Object
Dim oNewRow As ListRows
Dim itemName As String
Dim itemData As Long
Dim r As Integer
Dim rng As Range
Set tblThings = ActiveSheet.ListObjects("tblThings")
Set tblNew = ActiveSheet.ListObjects("tblNew")
itemName = "Thing1"
''''Create rng here
For Each r in rng
Set oNewRow = tblNew.ListRows.Add(AlwaysInsert:=True)
oNewRow.Range.Cells(1, 1) = itemName
oNewRow.Range.Cells(1, 2) = itemData
Next
End Sub
I have been able to get the number of rows containing Thing1 using a CountIf line, but that isn't quite what I need. I can't seem to figure out any good way to do this. Thanks for any assistance!