radsok8199
New Member
- Joined
- Dec 4, 2020
- Messages
- 24
- Office Version
- 2016
- Platform
- Windows
- MacOS
- Mobile
Dear VBA Masters
I wrote code to use Vlookup. It seems like there is still some issue and I cannot get what is wrong.
So on Sheet1 I have a Table2. Column C of it is my primary key ( lookup value).
On Sheet2 I have Table1. Column A contains primary key ( lookup value) but in different order. This table contains amount of columns with values
So below code should take look up values from Table2 and search row for with it in Table 1. Get value from this row for each column ( column number index will change with loop) and place this value in requested location. Once all rows are done it will do same for another column.
However it loops only for 11 rows and place values 2 columns forward then comes with Run time error 1004.
It should start placing values 2 column ahead from table1.
What i am doing wrong here ?
I wrote code to use Vlookup. It seems like there is still some issue and I cannot get what is wrong.
So on Sheet1 I have a Table2. Column C of it is my primary key ( lookup value).
On Sheet2 I have Table1. Column A contains primary key ( lookup value) but in different order. This table contains amount of columns with values
So below code should take look up values from Table2 and search row for with it in Table 1. Get value from this row for each column ( column number index will change with loop) and place this value in requested location. Once all rows are done it will do same for another column.
However it loops only for 11 rows and place values 2 columns forward then comes with Run time error 1004.
It should start placing values 2 column ahead from table1.
What i am doing wrong here ?
VBA Code:
Sub loopTest()
Dim shtE As Worksheet
Dim shtS As Worksheet
Dim c As Long
Dim r As Long
Dim lrowS As Long
Dim lcolS As Long
Dim lcolE As Long
Dim Incol As Long
Set shtS = ThisWorkbook.Worksheets("Sheet1")
Set shtE = ThisWorkbook.Worksheets("Sheet2")
lrowS = shtS.Cells(shtS.Rows.Count, "C").End(xlUp).Row
lcolS = shtS.ListObjects("Table2").Range.Columns.Count
lcolE = shtE.ListObjects("Table1").Range.Columns.Count
For c = 2 To lcolE
For r = 2 To lrowS Step 1
Incol = lcolS + c
shtS.Cells(r, Incol + c).Value = WorksheetFunction.VLookup(shtS.Cells(r, 3).Value, shtE.Range("Table1"), c, 0)
Next r
Next c
End Sub