Home » excel » visual studio 2010 – how to create custom function in excel to grab mysql data?

visual studio 2010 – how to create custom function in excel to grab mysql data?

Posted by: admin May 14, 2020 Leave a comment

Questions:

We need to create a custom formula for users to pull data from our mysql database. After the user is authenticated, they would type in a formula in excel (something like ‘=retrievemybirthday(“Frank Dodge”)’. How do we go about doing that? We’re not new to programming, just new to programming w/ Excel. Are there any tutorials on this? We’ve looked but can find anything.

thanks!

How to&Answers:

1) you need an ODBC driver configured for your MySQL db.

2) figure out the SQL code you need for this function, something like

select birthdate
from YourTable
Where membername=?

You will use this code in your function

3) In your function, you will need the correct Connection String. Check a site like http://www.connectionstrings.com/

4) Here’s an example of a function, using ActiveX Data Objects (you need a reference set in Tools > References in the VB Editor)

Function GetNomen(sPN As String) As String
'SkipVought/2006 Mar 7
'--------------------------------------------------
' Access: DWPROD.FRH_MRP.READ
'--------------------------------------------------
':this function returns nomenclature for a given part number
'--------------------------------------------------
'2011-9-26 Converted to Parameter Query
'--------------------------------------------------

    Dim sConn As String, sSQL As String, sServer As String
    Dim rst As ADODB.Recordset, cnn As ADODB.Connection, cmd As ADODB.Command

    Set rst = New ADODB.Recordset
    Set cnn = New ADODB.Connection
    Set cmd = New ADODB.Command

    sServer = "dwprod"
    cnn.Open "Driver={Microsoft ODBC for Oracle};" & _
               "Server=" & sServer & ";" & _
               "Uid=/;" & _
               "Pwd="

    sSQL = "SELECT PM.Nomen_201 "
    sSQL = sSQL & "FROM FRH_MRP.PSK02101 PM "
    sSQL = sSQL & "WHERE PM.PARTNO_201 =?"


    Debug.Print sSQL

   With cmd
        .CommandText = sSQL
        .CommandType = adCmdText
        .Prepared = True

        .Parameters.Append .CreateParameter( _
            Name:="PARTNO_201", _
            Type:=adChar, _
            Direction:=adParamInput, _
            Size:=16, _
            Value:=sPN)

        .ActiveConnection = cnn

        Set rst = .Execute
    End With

    rst.MoveFirst

    If Err.Number = 0 Then
        GetNomen = rst("NOMEN_201")
    Else
        GetNomen = ""
    End If

    rst.Close
    cnn.Close

    Set cmd = Nothing
    Set rst = Nothing
    Set cnn = Nothing
End Function

You can run this function on the sheet as requested.