简体   繁体   中英

How to store and use a VBA Function within a worksheet (not workbook)

I keep hunting for an answer on this but seem to be out of luck.

I have a custom Function that I wish to store within a single worksheet such that the function can be distributed with the worksheet (ie not the workbook)

The custom function needs to be called from an excel cell formula

Calling the function when stored in a code module works fine however moving it into the worksheet object 'module' causes it to fail. This is perhaps to be expected.

The reason for wanting the Function placed in the sheet code is so that it is automatically imported with the sheet to a new workbook via the templates folder and can then be used by the rest of the workbook. (this being importing via the Insert>New Sheet Dialog

So my question is 2 fold, either:

How can call a function from an excel formula when the function is written in the worksheet code, or...

How can I automate a module being added to a new workbook when I add a sheet from a template file?

Of note, using the personal.xlsb file will not work for this and I need to be able to call the function from within a sheet formula

Thanks in advance

You can add the following to the ThisWorkbook events, of the workbook the sheet is being imported to, tweak as you like. I have a worksheet function in Sheet1, called ns it takes two arguments a and b , the function in excel I wish to use is MY_FUNCTION

This adds a module to hold the wrapper to the worksheet function.

Private Sub Workbook_NewSheet(ByVal Sh As Object)

Dim vbp As VBProject
Dim vbm As VBComponent

Set vbp = Application.VBE.ActiveVBProject

Set vbm = vbp.VBComponents.Add(vbext_ct_StdModule)
vbm.Name = "MY_FUNCTION_MDL"

'   vbm.CodeModule.AddFromFile ""       '   <--- another way add from file

vbm.CodeModule.InsertLines 1, "Public Function MY_FUNCTION(a,b)"
vbm.CodeModule.InsertLines 2, "     MY_FUNCTION=sheet1.ns(a,b)"
vbm.CodeModule.InsertLines 3, "End Function"

End Sub

You can do this (it works for me):

Option Explicit

Private Sub Workbook_Open()

   ThisWorkbook.VBProject.VBComponents.Import "[PathtoDir]\MyMod.bas"

End Sub

Make sure to do the following in excel:

安全

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM