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

标签 database vba excel ms-access

我有一个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/

相关文章:

database - 在使用文件哈希数据库的 Kyoto Cabinet 数据库中,如何避免文件大小增加?

VBA - 在公式中使用 Columns()

excel - VBA - 用户表单新实例

excel - 在 JavaFx 中嵌入 Excel

c# - 无法通过 OleDbAdapter 更新 Access 数据库

python - 如何在django运行时切换到多个数据库中的单个数据库?

database - SVN E155016 ... 的工作副本数据库已损坏

VBA/.Net 通过 Windows 安全从受密码保护的网站下载文件

vba - 读取 Excel 文件的 VBA 宏(或 vbaProject.bin),而无需在 MS Excel 中打开它

c# - 使用 .Net Interop 从 Excel 获取 DateTime 值时缺少毫秒数