Quantcast
Channel: Excel Help Forum - Excel Programming / VBA / Macros
Viewing all articles
Browse latest Browse all 50214

UDF to fetch value from another sheet gives #NAME? error

$
0
0
Hi,


I'm trying to create a UDF that can fetch a value from a cell in another sheet. It gives a #NAME? error, though.

The way I want it to work is this:
As input, it takes two cell references and a value, e.g.;
=ValueFetcher(A9;C9;1)

One cell (A9) contains the name of the sheet to look in. One cell (C9) contains a Column name, "ColName". The UDF should then, in that sheet:
1 Search cells A1:A50 to find a cell with the string "Country"
2 In the row X when the A-cell is "Country", it should search the 50 cells to the left of cell AX for the value "ColName".
3 When it has identified this, if should go down by 1 cell (as the "1" specified when calling the function
4 And lastly, it should give back the value of this cell


This is my unsuccessful attempt, that gives the #NAME? error. Any input on this would be greatly appreciated.

Alfred


Code:

Public Function ValueFetcher(SheetName As Range, ColName As Range, DownByX As Integer) As Integer
 
Dim SearchColumn As Range
Dim ColVar As Range
Dim SearchRow As Range
Dim TargetCell As Range


Set SearchColumn = Sheets(SheetName).Range("A1:A50")

For Each Cell In SearchColumn
    If Cell.Value = "Country" Then
        ColVar = ActiveCell.Address
    Else
        Exit For
    End If
Next

Set SearchRow = Sheets(SheetName).Range(ColVar, ColVar.Offset(0, 50))

For Each Cell In SearchRow
    If Cell.Value = ColName Then
    TargetCell = ActiveCell.Offset(DownByX, 0)
Else
    Exit For
End If
Next

ValueFetcher = TargetCell.Value

End Function


Viewing all articles
Browse latest Browse all 50214

Trending Articles