VBA Excel: User Defined Function

862 Views Asked by At

FIXED: check user3964075's comment

Need help with my simple code below: it's basically a different version of vlookup where you can also specify which row to look for.

asda(fval, rng, fcol, rcol)

fval is what the user is looking for

rng is the range

fcol is by vlookup default, set to 1, now the user can pick which column to use as basis for the search

rcol is the column which will be returned if match is found

See code below:

Function asda(fval As Range, rng As Range, fCol As Integer, rCol As Integer)

    Dim row As Variant

    For Each row In rng.Rows
        If fval.Value = rng.Columns(fCol).Rows(row).Value Then
            result = rng.Columns(rCol).Rows(row).Value
            GoTo found
        End If
    Next

found:
    asda = result

End Function

Problem: It does not work and I don't know why. Inasmuch as I'd like to use other people's code, I'd want to start with mine and fix it.

Fixed code to anyone reading this in the future:

Function asda(fval As Range, rng As Range, fCol As Integer, rCol As Integer)
Dim row As Variant
Dim rowc As Integer

rowc = 1
For Each row In rng.Rows
    If fval.Value = rng.Cells(rowc, fCol).Value Then
        result = rng.Cells(rowc, rCol).Value
        Exit For
    End If
    rowc = rowc + 1
Next

asda= result

End Function

1

There are 1 best solutions below

2
On BEST ANSWER

Look at the comments for the first explaination.

And as you were using row as a variable you couldn't call the Row Property from the Range class, so I changed it to RowV to use RowV.row.

Compiling what have been said :

Function asda(fval As Range, rng As Range, fCol As Integer, rCol As Integer)

    Dim RowV As Range

    For Each RowV In rng.Rows
        If fval.Value <> rng.Cells(RowV.row, fCol).Value Then
        Else
            asda = rng.Columns(rCol).Rows(RowV.row).Value
            'Exit For
            Exit Function
        End If
    Next RowV

    asda = "Value not found"

End Function