Find instances of a string in a table and using their rows

Status
Not open for further replies.

Jimithy

New Member
Joined
Apr 5, 2018
Messages
8
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
NameData
Thing111
Thing233
Thing155
Thing377

<tbody>
</tbody>

tblNew (I should note other rows besides the new ones already existed, but are not shown here)
NameData
Thing111
Thing155

<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!
 

Some videos you may like

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
46,303
Office Version
  1. 365
Platform
  1. Windows
Duplicate https://www.mrexcel.com/forum/excel...-instances-string-table-using-their-rows.html

Please do not post the same question multiple times. All clarifications, follow-ups, and bumps should be posted back to the original thread.
Per forum rules, posts of a duplicate nature will be locked or deleted (rule 12 here: Forum Rules).

Note that sometimes posts from new users require Moderator approval before you can see them on the public forums. When this happens, you should see a message to that effect when you try to post it.
Please be patient and do not attempt to post the question again.
 
Status
Not open for further replies.

Watch MrExcel Video

Forum statistics

Threads
1,108,973
Messages
5,525,986
Members
409,673
Latest member
Riseee

This Week's Hot Topics

Top