我有一个access 2013的数据库
日期 |数据
2015 年 1 月 6 日 | 1
2015 年 2 月 6 日 | 2
我想编写一个从数据库返回值的函数。
=GETDATA("FORDATE")
这可能吗? 我已经试过了,但它不想工作
Public Function GetData(id As Date) As String
Set oConnection = New ADODB.Connection
Dim oRecordset As ADOR.Recordset
oConnection.Open "Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\user\Desktop\CAINV_DB.accdb;" & "Trusted_Connection=yes;"
Set oRecordset = oConnection.Execute("select " & RDATE & " from CB_EXCHANGE where RDATE = " & id)
If oRecordset.EOF Then
GetData = "n/a"
Else
GetData = oRecordset(1)
End If
End Function
最佳答案
所以你需要使用这段代码(插入你的数据库路径):
Public Function getData(whatDate As Date) As Variant
Dim DB As Database
Dim RS As Recordset
Set DB = DBEngine.OpenDatabase("C:\temp\Desktop\Test.mdb")
Set RS = DB.OpenRecordset("SELECT USD FROM CB_EXCHANGE WHERE RDate = #" & Format(whatDate, "m\/d\/yyyy") & "#", dbOpenDynaset) ' The date format must be like this
If RS.RecordCount > 0 Then
RS.MoveFirst
getData = RS!USD ' of course you must enter the correct column name
End If
End Function
关于database - 如何编写从 ACCESS 数据库返回值的 Excel 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31267776/