Search code examples
excelvbamatch

If value matches x, enter new value into another table using row and column matches


I'm using Excel 365 and trying to take advantage of VisualBasic for this query. I'm working with two tables where if Table: EventDiary[Match] = 1 then I want to enter the [Actual] value (-30) into Table Sim.

The value will replace the cell's contents in Table: Sim (which is currently 60). The column is found via EventDiary[L] which equals 2. The row is found via EventDiary[Index] which equals 3.

How would I achieve this?

Table Name: EventDiary

L Match Index Actual
2 1 3 -30
4 0 0 0
6 0 0 0

Table Name: Sim

Index 1 2 3 4 5 6
1 51 24
2 9 15
3 12 60

Solution

  • This VBA code is just does what is described in the question, with static column references as of the screenshot.
    Sheet1 is the sheet's name where the two tables are placed.

    Sub copyrepl()
    matchval = 1
    Dim s1 As ListObject, t1 As ListObject
    Set s1 = Sheet1.ListObjects("EventDiary")
    Set t1 = Sheet1.ListObjects("Sim")
    'Set t1 = Sheet2.ListObjects("Sim")  if the Sim table is on Sheet2
    colvalue = s1.DataBodyRange.Columns(2).Find(matchval, , xlFormulas, xlWhole).Row
    actvalue = Sheet1.Cells(colvalue, 4)  
    indvalue = Sheet1.Cells(colvalue, 3)
    colvalue = Sheet1.Cells(colvalue, 1)
    rowvalue = t1.DataBodyRange.Columns(1).Find(indvalue, , xlFormulas, xlWhole).Row
    colvalue = t1.HeaderRowRange.Find(colvalue, , xlFormulas, xlWhole).Column
    Cells(rowvalue, colvalue) = actvalue
    'Sheet2.Cells(rowvalue, colvalue) = actvalue  if the Sim table is on Sheet2
    End Sub
    

    enter image description here