Saturday, December 14, 2019

Excel Add-ins with User defined functions

Excel Add-ins with User defined functions


Excel allows to create User defined function which work same way as those in-build functions/formulas. For example if you want to get just hostname from FQDN it's easy you can do this:
=Left(A1, InStr(A1, ".") - 1)
The problem is when you need to do it more often it's easier to create function like below and just used =Hostname(A1)

Function Hostname(FQDN As Variant) As Variant
    Hostname = Left(FQDN, InStr(FQDN, ".") - 1)
End Function

Even better example happend to me recently. I've got the IP in log but it was in reverse order so I need to reverse it back (140.255.15.10 to 10.15.255.140) and compare to list to figure which devices are logging and which not. It's easy you split data, delimited by dot, and do =concat(D1,".",C1,".",B1,".",A1) when I done this for 3rd time I decide it's case for UDF. And as I was creaitng reverseIP(IP) function I decide I can create whole set of network related functions.
Here you have it, I hope you will like it. https://github.com/kindljiri/Excel-Add-Ins-and-Macros
You'll find two files there xlam which is excel add-in and bas which is VBA code for the same in case you don't trust my xlam.
Below is how you can create your Add-in, you can copy my code and paste it in.

Creating Add-in


Open New Excel
Go To developers Tab
Open Visual Basic

Write you functions.
the variable with same name as function have to be assigned some value. That will be then displayed as result. For example:
Function ReverseIP(text As Variant) As Variant
  Octets = Split(text, ".")
  ReverseOctets = Array(Octets(3), Octets(2), Octets(1), Octets(0))
  ReverseIP = Join(ReverseOctets,".")
End Function

You can use then this function as any other excel function/formula
=reverseIP(A1)

Save Add-in


To save Add-in go in
Excel to Save As (pick any folder)
As format choose Excel Add-in (*.xlam) it will change the folder to default folder from which Excel is loading Add-ins
Remember to activate the plugin to be able to use functions inside.


Activate Add-in


Go to Developer tab and Click on Excel Add-ins check the Add-in which you wanna activate.


Install Add-In


Just copy the Add-in file *.xlam into C:\Users\G33k\AppData\Roaming\Microsoft\AddIns
And Activate it.