Home » excel » Excel VBA Vlookup issue

Excel VBA Vlookup issue

Posted by: admin May 14, 2020 Leave a comment


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 only in one other place. It seemed best suited.

How to&Answers:

Fixing your code
You should use Wend not End While for your loop.

Cleaner Alternative
But you can fill an entire range in a single shot as below

  1. It is better to “loop up” a range from the bottom using End(xlup) than to look down with End(xlDown) (which relies on no spaces)
  2. You almost never need to use Select in VBA

Further explanation

  1. rng1 sets a working range from the last used cell in column A in sheet datasheet to A3
  2. rng1.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
  3. I used the macro recorder to get the code you needed in column N for this part "=VLOOKUP(RC[-1],'GICS Sub-industry codes'!R2C1:R155C2,2,FALSE)".
  4. IN R1C1 speak, RC[-1] means refer to the cell in the same row, but one column to the left. So in N3, the formula will start as =VLOOKUP(M4..), So in N30, the formula will start as `=VLOOKUP(M30..) etc

Suggested code

Sub QuickFill()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("datasheet")
Set rng1 = ws.Range(ws.[a3], ws.Cells(Rows.Count, "A").End(xlUp))
rng1.Offset(0, Range("N1").Column - 1).FormulaR1C1 = "=VLOOKUP(RC[-1],'GICS Sub-industry codes'!R2C1:R155C2,2,FALSE)"
End Sub