Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I try to use a VBA function that I've defined in an Excel spreadsheet, I get "That is not a valid function"

Tags:

excel

vba

I defined a function in VBA as follows

Public Function Distance(X, Y) as Double

Then in a cell I try to use the function. I type "@Dis" and get the drop down menu, select the function and then enter the parameters ending up with @Distance(A1, A2) in the cell.

When I press Enter I get the Error "That function is not valid".

I enabled macros throughout the system, tried saving it as the old format and as the macro enabled workbook format to no avail.

What's wrong with my usage of this function?

like image 305
Matt Avatar asked May 21 '09 16:05

Matt


People also ask

How do I use a VBA function in a spreadsheet?

Insert VBA code to Excel Workbook Open your workbook in Excel. Press Alt + F11 to open Visual Basic Editor (VBE). Right-click on your workbook name in the "Project-VBAProject" pane (at the top left corner of the editor window) and select Insert -> Module from the context menu. Copy the VBA code (from a web-page etc.)

Can a function in VBA be used in an Excel formula?

When you have created a Function procedure using VBA, you can use it in three ways: As a formula in the worksheet, where it can take arguments as inputs and returns a value or an array of values. As a part of your VBA subroutine code or another Function code. In Conditional Formatting.

Why not use VBA Excel?

Sometimes writing, testing and debugging the script will take longer than using worksheet features. VBA does not adjust in the way that formulae do when you move data from one worksheet to another, insert a column, delete rows, etc. Example: you have a sheet called February. Now you want to rename it Feb.


2 Answers

Try using:

=Distance(A1, A2)

Instead of

@Distance(A1, A2)

I've never seen @ as the correct character to call a function in Excel.

I tried the following in Excel, and it works like a charm:

In Module1:

Public Function Distance(X as Double, Y as Double) as Double
    Distance = 10
End Function

In a cell:

=Distance(A1, A2)

Which produces the result:

10

as expected.

like image 176
e.James Avatar answered Sep 23 '22 22:09

e.James


You'll also need to make sure that the VBA code for your function is in a Module and not in the code area of the Worksheet.

like image 45
Mark Biek Avatar answered Sep 22 '22 22:09

Mark Biek