简体   繁体   中英

VBA for vlookup giving a compile error

I have a vlookup VBA script that when I go to run it, gives me a Compile error: Next without For. I have searched this site and others and found post with similar issues, but can't seem to find a fix for mine.

My main goal here is to VLookup an invoice account in cells T8:T50, and if the Range L8:L50 is blank, to fill in the name of the person responsible for that account.

Sub lookup()
Dim r As Range
Set r = Sheet1.Range("L8:L50")

    If r = "" Then
        Range("L8") = Application.WorksheetFunction.VLookup(Sheets("Sheet1").Range("T8:T50"), Sheets("Sheet3").Range("A:B"), 2, False)
    End If
    Next r

End Sub

For Each requires Next (which in turn can't be used with For Each or For ). You need to initiate a loop over the range of cells in column L. Use Application.Vlookup instead because it allows returning an error value without raising it to the procedure, then you can use IsError to check for potential errors and just put a placeholder value in worksheet instead.

The Offset function says "Use the value in the cell 8 columns to the right of the current iterator r " (which is in column L), so if my math is right, L + 8 = T.

Dim val, r As Range
Dim lookupRange as Range, accountRange as Range
Set lookupRange = Sheets("Sheet3").Range("A:B")
Set accountRange = Sheets("Sheet1").Range("L8:L50")
For Each r in accountRange.Cells
    If r.Value = "" Then
        val = Application.VLookup(r.Offset(0,8).Value, lookupRange, 2, False)
        If IsError(val) Then
            r.Value = "Error!"
        Else
            r.Value = val
        End If
    End If
Next r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM