How to Call VBA Function from Excel Cells?

calendar_today Asked Oct 26, 2013
thumb_up 16 upvotes
history Updated April 16, 2026

Question posted 2013 · +7 upvotes

I am a VBA newbie, and I am trying to write a function that I can call from Excel cells, that can open a workbook that’s closed, look up a cell value, and return it.

So far I know how to write a macro like this:

Sub OpenWorkbook()
    Dim path As String
    path = "C:UsersUserNameDesktopTestSample.xlsx"

    Dim currentWb As Workbook
    Set currentWb = ThisWorkbook


    currentWb.Sheets("Sheet1").Range("A1") = OpenWorkbookToPullData(path, "B2")
End Sub


Function OpenWorkbookToPullData(path, cell)

    Dim openWb As Workbook
    Set openWb = Workbooks.Open(path, , True)

    Dim openWs As Worksheet
    Set openWs = openWb.Sheets("Sheet1")

    OpenWorkbookToPullData = openWs.Range(cell)

    openWb.Close (False)

End Function

The macro OpenWorkbook() runs perfectly fine, but when I am trying to call OpenWorkbookToPullData(…) directly from an Excel cell, it doesn’t work. The statement:

    Set openWb = Workbooks.Open(path, , True)

returns Nothing.

Does anyone know how to turn it into a working VBA function that can be called from Excel cell?

Accepted answer +16 upvotes

Here’s the answer

Steps to follow:

  1. Add a new module from the Visual Basic Editor (In Excel, hit Alt+F11 on Windows / fn+option+F11 on a Mac).
  2. Create a Public function. Example:

    Public Function findArea(ByVal width as Double, _
                             ByVal height as Double) As Double
        ' Return the area
        findArea = width * height
    End Function
    
  3. Then use it in any cell like you would any other function: =findArea(B12,C12).

Excel VBA objects referenced (5)

  • Range — Refer to Cells by Using a Range Object
  • Range — Delete Duplicate Entries in a Range
  • Workbook — Workbooks and Worksheets
  • Workbook — Add a Table of Contents to a Workbook
  • Worksheet — Refer to All the Cells on the Worksheet

Top excel-vba Q&A (6)

+16 upvotes ranks this answer #27 out of 136 excel-vba solutions on this site — top 20%.