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:\Users\UserName\Desktop\TestSample.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?
Find and Highlight Duplicates in a Column Using Excel VBA ❶ First of all, press ALT + F11 to open the VBA editor. ❷ Then go to Insert >> Module. ❸ Copy the following VBA code. ❹ Paste and Save the code in the VBA editor.
Steps to follow: In Excel, hit Alt + F11 if on Windows, Fn + Option + F11 if on a Mac. Insert a new module. From the menu: Insert -> Module (Don't skip this!). Then use it in any cell like you would any other function: =findArea(B12,C12) .
In this case, we have headers, so select “xlYes.” Run this code. It will VBA remove duplicates from the selected region. This is an explicit way of referring to the range of cells.
Here's the answer
Steps to follow:
Open the Visual Basic Editor. In Excel, hit Alt+F11 if on Windows, Fn+Option+F11 if on a Mac.
Insert a new module. From the menu: Insert -> Module (Don't skip this!).
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
Then use it in any cell like you would any other function: =findArea(B12,C12)
.
The issue you have encountered is that UDF
s cannot modify the Excel environment, they can only return a value to the calling cell.
There are several alternatives
For the sample given you don't actually need VBA. This formula will work='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2
Use a rather messy work around: See this answer
You can use ExecuteExcel4Macro
or OLEDB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With