views:

237

answers:

2

I want to write a Excel function like this. It is an extension of the Dec2Bin function

Public Function Dec2BinEx(x As Long)
  Dec2BinEx = dec2bin(x) + 10
End Function

But I am getting an error when trying to use it. How do I call a excel function inside the visual basic editor

A: 

You will first of all have to create a module eg from menu select Insert->Module. Then inside this module create a function named main. This function is run by default when code is run. Now inside this function call your own function like this:

Sub main()
    Call Dec2BinEx(your_value_here)
End Sub

Public Function Dec2BinEx(x As Long)
    Dec2BinEx = dec2bin(x) + 10
End Function

Having done that, make sure that you have the reference to dec2bin function or if you create that too. Thanks

Sarfraz
Sarfraz,for an Excel user-defined function to be called from a worksheet you don't need a MAIN sub.
Charles Williams
@Charles: thanks for letting me know about that, it has been long time since i have stopped working on this. Thanks
Sarfraz
+4  A: 

In general, you call Excel functions with Application.WorksheetFunction.SomeFunctionName. However, Dec2Bin is special, as it is an Add-In function, and not a pure Excel function. Hence, Application.WorksheetFunction does not work here. Instead, you have to make the functions of the add-in available to your code. To do so, follow these steps

  • In Excel, menu Tools/Add-Ins, make sure that the add-in Analysis ToolPak - VBA is imported.

  • Then, set a reference to this add-in in your code: in the VBA editor, menu Tools/References, add a reference to atpvbaen.xls.

Then, your original code, as posted in your quesiton should work just fine.

stephan
Thanks. This works. I am also trying to call the Mod() function inside. Is there anything that needs to be referenced to support the Mod function in the VBA code
Karthick
@Karthick: in VBA, there exists a Mod operator (http://msdn.microsoft.com/en-us/library/aa164528%28office.10%29.aspx) that you can use. Instead of the worksheet function `=Mod(10,3)`, you write `10 Mod 3` in your code.
stephan
Thanks Stephan. This works fine.
Karthick