Home » excel » vba – Excel UDF to reference table in closed workbook for lookup

vba – Excel UDF to reference table in closed workbook for lookup

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a working UDF which assigns a user name based on the first letter of a selected cell. The alphabet and user name list are built into the function in VBA therefore updates are tedious so I’m searching for an alternative.

I created a table within a workbook where the assignments can be updated more easily and by anyone. I’ve made several efforts however I cannot get the UDF to properly assign user name by looking up the table. One attempt is below, either I’m way off the mark or this cannot be done. Thoughts?

Function Test(Optional Cell As String) As String
Dim Name As Variant, Alpha As Variant, ATable As Variant
Dim i As Integer

If UCase(Left(Cell, 1)) = "A" Then
    Alpha = UCase(Left(Cell, 2))
Else: Alpha = UCase(Left(Cell, 1))
End If

ATable = Workbook("C:\filepath\").Worksheets("sheet1").ListObjects("ALPHA").DataBodyRange.Value

For i = LBound(ATable) To UBound(ATable)
    If ATable(i, 1) = Alpha Then
        Name = ATable(i, 2)
    End If
Next i

Test = Name

End Function

The UDF is designed to be used in any open workbook and table workbook would be closed.

How to&Answers:
  1. To get a data from a closed workbook you have to open it – Pulling data from a closed workbook macro

  2. A UDF cannot open a workbook. Description of limitations of custom functions in Excel.