如何编写从ACCESS数据库返回值的Excel函数?

时间:2015-07-07 11:50:26

标签: database vba excel-vba ms-access excel

我在Access 2013中有一个数据库

日期|数据

01/06/2015 | 1

02/06/2015 | 2

我想写一个从DB返回值的函数。

=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

2 个答案:

答案 0 :(得分:2)

因此您需要使用此代码(插入数据库路径):

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

答案 1 :(得分:1)

首先,您需要引用“Microsoft DAO 3.6对象库”。我不知道菜单是如何在英文版VBA编辑器中命名的。在德语版本中,它是“Extras> Verweise ......”

然后你需要这样的代码:

Public Function getData(Data as Integer) As Variant
Dim DB As Database
Dim RS As Recordset

Set DB = DBEngine.OpenDatabase("C:\yourPath\yourDatabase.accdb")
Set RS = DB.OpenRecordset("SELECT foo FROM bar WHERE Data = " & Data, dbOpenDynaset)

If RS.RecordCount > 0 Then
    RS.MoveFirst
    getData = RS!Date
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:\yourPath\yourDatabase.accdb")
Set RS = DB.OpenRecordset("SELECT Data FROM CB_EXCHANGE WHERE Date = #" & Format(Date, "m\/d\/yyyy") & "#", dbOpenDynaset)

If RS.RecordCount > 0 Then
    RS.MoveFirst
    getData = RS!Data
End If

End Function