I’m a complete beginner to Excel VBA.
The following is code I’ve written that should iterate through a column in a sheet, filling values by referring to the column value to it’s left and referring to another sheet in the same workbook to find what the correct corresponding value should be.
I’ve used a While loop so i can apply this VLOOKUP macro to each cell in the column ( only the lookup value, changes, which should be a variable denoting the column to the left) :
Dim result As String
Dim sheet As Worksheet
Dim rownum As Integer
Dim iterator As Integer
Dim lookup_value As String
Dim vlookupString1 As String
Set sheet = ActiveWorkbook.Sheets("datasheet")
rownum = sheet.Range("A1").End(xlDown).Row
Set iterator = 3
While iterator < rownum
lookup = "M" & iterator
vlookup1String = "=VLOOKUP(" & lookup & ",'GICS Sub-industry codes'!$A$2:$B$155,2,FALSE)"
With ActiveSheet.Cells
Range("N" & iterator).Select
Selection.Value = vlookup1String
End With
iterator = iterator + 1
End While
I’m getting an error @ end while saying “expected if or select or sub…”
1) Have i made a syntax error?
2) Is my approach correct. I have observed this string approach to designing VLOOKUPS in vba only in one other place. It seemed best suited.
Fixing your code
You should use
WendnotEnd Whilefor your loop.Cleaner Alternative
But you can fill an entire range in a single shot as below
End(xlup)than to look down withEnd(xlDown)(which relies on no spaces)Selectin VBAFurther explanation
rng1sets a working range from the last used cell in column A in sheet datasheet to A3rng1.Offset(0, Range("N1").Column - 1)says offset rng1 (which is column A) by 13 columns to use column N (ie OFFSET A by 14-1) for the formula insertion"=VLOOKUP(RC[-1],'GICS Sub-industry codes'!R2C1:R155C2,2,FALSE)".R1C1speak,RC[-1]means refer to the cell in the same row, but one column to the left. So inN3, the formula will start as=VLOOKUP(M4..), So inN30, the formula will start as `=VLOOKUP(M30..) etcSuggested code