我想创建一个自定义excel函数,它将单元格值作为参数来查询mysql数据库
Function excelmysql2()
Dim odjDB As ADODB.Connection
Dim sqlstr As String
Dim rs As ADODB.Recordset
Dim oRS, nRec, oFld
Dim Row
'----------------------------------------------------------------------
Set odjDB = New ADODB.Connection
Sheets("Sheet1").Select
odjDB.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=192.168.0.64;" & _
"DATABASE=mifos;" & _
"Port=3307;" & _
"USER=root;" & _
"PASSWORD=admin;"
Set oRS = odjDB.Execute("SELECT account.customer_id FROM mifos.account WHERE (mifos.account.account_id= '" & Range("A3").Value & "')")
nRec = 0
Row = 3
Do While Not oRS.EOF
For Each oFld In oRS.Fields
Worksheets("Sheet1").Cells(Row, 3).Value = oRS("customer_id")
Row = Row + 1
On Error Resume Next
oRS.MoveNext
Next
Loop
oRS.Close
odjDB.Close
End Function
正如您所注意到的那样,在函数中设置了单元格编号 因为我无法找到让它变得动态的方法。 我想能够像任何excel函数一样使用函数,我可以传递一个单元格的值并从mysql获取查询值
我应该放置什么而不是Range(" A3")才能通过传递单元格值在excel中使用此函数? (EX:= excelmysql2(A1)...)
感谢
答案 0 :(得分:0)
以下例如。与您的问题有关
使用它,只需更改参数....
它说明了一个查询,该查询返回基于月份和年份的汇率{收盘汇率"MEND"
)来自名为finance的数据库中名为费率的表
SELECT rates.MEND FROM rates WHERE rates.Cur = 'USD' AND rates.Month = JAN AND rates.Year = 2015 returns 14.35
表:费率
Cur |本月|年| MEND
ZAR | JAN | 2015年| 1.453
美元| JAN | 2015年|的 14.35 强>
Function MySQL_Month_endRate(Curr As String, Monn As Integer, yearr As Integer) As String
'##################
'## Connection ##
'##################
Dim conn As Variant
Dim rs As Variant
Dim cs As String
Dim query As String
Dim Table_Name As String
Table_Name = "rates"
Dim Database_Name As String
Database_Name = "finance"
Set conn = CreateObject("adodb.connection")
Set rs = CreateObject("adodb.recordset")
cs = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
cs = cs & "DATABASE=" & Database_Name & ";"
cs = cs & "SERVER=127.0.0.1"
conn.Open cs, "root", "root" 'UserName and Password else WindowsNT Autentication
'####################
'## QUERY ##
'####################
query = "SELECT rates.MEND FROM rates WHERE rates.Cur = '" & Curr & "' AND rates.Month = " & Monn & " AND rates.Year = " & yearr
'Curr As String, Monn As Integer, yearr As
Debug.Print query
rs.Open query, conn
'####################
'## RECORD SET ##
'####################
Do Until rs.EOF
' row = row + 1
' Cells(row, 5).Value = rs.Fields("Serial key").Value
Debug.Print rs.Fields("MEND").Value
MySQL_Month_endRate = rs.Fields("MEND").Value
rs.MoveNext
Loop
'#####################
'## Return ##
'#####################
Set rs = Nothing
conn.Close
Set conn = Nothing
'myRibbon.Invalidate
'End
errline:
If Err.Description <> "" Then MsgBox Err.Description
'MsgBox Err.Description
End Function