Monday, September 19, 2011

Excel User Defined Function for CIDR Subnet Mask Notation

Here's another one of the Excel UDF's I have prepared for performing network operations in Excel. I find it specifically useful when dealing with large data sets. This function converts a subnet mask to CIDR notation. It is implemented with statically defining a dictionary object. It may not be an elegant solution, but it is works.

Ex. CIDR("")=9

'CIDR (Classless Inter-Domain Routing)
'Given an inputStr value containing a subnet mask in an IP 
'format this functio returns the corresponding subnet mask 
'in CIDR Notation
Function cidr(inputStr As String)
    Dim maskDict As Dictionary
    Set maskDict = New Dictionary
    maskDict.Add "", 1
    maskDict.Add "", 2
    maskDict.Add "", 3
    maskDict.Add "", 4
    maskDict.Add "", 5
    maskDict.Add "", 6
    maskDict.Add "", 7
    maskDict.Add "", 8
    maskDict.Add "", 9
    maskDict.Add "", 10
    maskDict.Add "", 11
    maskDict.Add "", 12
    maskDict.Add "", 13
    maskDict.Add "", 14
    maskDict.Add "", 15
    maskDict.Add "", 16
    maskDict.Add "", 17
    maskDict.Add "", 18
    maskDict.Add "", 19
    maskDict.Add "", 20
    maskDict.Add "", 21
    maskDict.Add "", 22
    maskDict.Add "", 23
    maskDict.Add "", 24
    maskDict.Add "", 25
    maskDict.Add "", 26
    maskDict.Add "", 27
    maskDict.Add "", 28
    maskDict.Add "", 29
    maskDict.Add "", 30
    maskDict.Add "", 31
    maskDict.Add "", 32
    cidr = maskDict.Item(FindIP(inputStr))
End Function

'Find IP Address
'A support function that parses input strTest through a regular 
'expression to find an IP Address
'A blank value is returned if no IP address can be found
Function FindIP(strTest As String) As String
    Dim RegEx As Object
    Dim valid As Boolean
    Dim Matches As Object
    Dim i As Integer
    Set RegEx = CreateObject("VBScript.RegExp")
    RegEx.Pattern = "\b(?:\d{1,3}\.){3}\d{1,3}\b"
    valid = RegEx.test(strTest)
    If valid Then
        Set Matches = RegEx.Execute(strTest)
        FindIP = Matches(0)
        FindIP = ""
    End If
End Function


  1. Helpful script but you need to add a reference to the Microsoft scripting runtime for it to work

  2. An IP (Internet Protocol) address is a logical address of a device in a computer network using IP protocol (works on Layer 3 of ISO/OSI model). IP addresses are used on the Internet. IP addresses are stored as 32-bit binary numbers, but they are displayed as four decimal numbers divided with a dot (dot-decimal notation), example An IP address indicates the logical location of a device. An IP address range is from to Public addresses are managed by IANA (Internet Assigned Numbers Authority) and blocks of addresses are allocated to Local Internet Registries. These address blocks correspondent to geological locations.