【问题标题】:how to create custom function in excel to grab mysql data?如何在excel中创建自定义函数来获取mysql数据?
【发布时间】:2011-11-22 19:48:33
【问题描述】:

我们需要为用户创建一个自定义公式,以便从我们的 mysql 数据库中提取数据。用户通过身份验证后,他们会在 excel 中输入一个公式(类似于 '=retrievemybirthday("Frank Dodge")'。我们该怎么做呢?我们对编程并不陌生,只是对 w/ Excel。有这方面的教程吗?我们看过了,但什么都能找到。

谢谢!

【问题讨论】:

    标签: mysql visual-studio-2010 excel excel-formula vba


    【解决方案1】:

    1) 您需要为您的 MySQL 数据库配置 ODBC 驱动程序。

    2) 找出此函数所需的 SQL 代码,例如

    select birthdate
    from YourTable
    Where membername=?
    

    您将在您的函数中使用此代码

    3) 在您的函数中,您将需要正确的连接字符串。检查类似http://www.connectionstrings.com/的网站

    4) 这是一个使用 ActiveX 数据对象的函数示例(您需要在 VB 编辑器的工具 > 引用中设置一个引用)

    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
    

    您可以根据要求在工作表上运行此功能。

    【讨论】:

    • "您可以根据要求在工作表上运行此功能。"。当用户输入 '=retrievemybirthday("Frank Dodge")' 时,我如何调用您的函数?
    • 正如您所指出的那样。顺便说一句,代码必须存在于 MODULE 中。
    猜你喜欢
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2010-10-19
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多