Hello Govert and the whole group. I did a practice of Excel DNA and the Excel DNA Interop DAO library. And it works but I have a problem with the StockPrice function when accessing the database in Access. My database has a coding field similar to that of the youtube video, with another date field and a field with the sales amount data whose value I want the function to show me but it gives me an error.
Imports Microsoft.Office.Interop.Access.Dao
Imports ExcelDna.Integration
Imports System.IO
Public Module StockData
Dim dbDemoData As Database
Dim rsTimeSeries As Recordset
Sub EnsureInitialized()
If dbDemoData Is Nothing Then
Dim dbpath As String = "D:\Practicas\Practicas\PracticaInteropDao1\DataEjemplo\DataPrueba.accdb"
dbDemoData = New DBEngine().OpenDatabase(dbpath)
rsTimeSeries = dbDemoData.OpenRecordset("PruebaData")
rsTimeSeries.Index = "ClavePrincipal"
End If
End Sub
' This would not be needed in VBA - in .NET we must instantiate the root COM object
Private MyDBEngine As New DBEngine()
Private MyDatabase As Database
Const MyDatabasePath As String = "D:\Practicas\Practicas\PracticaInteropDao1\DataEjemplo\DataPrueba.accdb"
Private Sub EnsureDatabaseIsConnected()
If MyDatabase Is Nothing Then
' We've not set the database yet - try to open or create a new one
If File.Exists(MyDatabasePath) Then
MyDatabase = MyDBEngine.OpenDatabase(MyDatabasePath)
Else
'Create New DB for testing - this could be OpenDatabase too
MyDatabase = MyDBEngine.CreateDatabase(MyDatabasePath, Locale:=LanguageConstants.dbLangGeneral)
'Add the tables Or give an error ....
' ...
End If
End If
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' These will be UDF functions you can call from a sheet...
' Check that the DAO is working correctly
<ExcelFunction(Description:="Returns the version of the loaded DAO DBEngine")>
Public Function DBEngineVersion() As Object
Return MyDBEngine.Version
End Function
' Check that the database was opened
<ExcelFunction(Description:="Returns the name of the open database")>
Public Function DatabaseName() As String
EnsureDatabaseIsConnected()
Return MyDatabase.Name
End Function
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This will be a macro added to the Add-Ins tab on the ribbon
<ExcelCommand(MenuName:="Excel-DNA DAO Sample", MenuText:="Show Database Name")>
Public Sub ShowDatabaseName()
EnsureDatabaseIsConnected()
MsgBox(MyDatabase.Name, Title:="DAO Sample")
End Sub
Function StockPrice(TheCode As String, TheDate As DateTime)
EnsureInitialized()
With rsTimeSeries
.Seek("<=", TheCode, TheDate)
If Not .NoMatch AndAlso .Fields!Code.Value = TheCode Then
Return .Fields!Close.Value
Else
Return ExcelError.ExcelErrorNA
End If
End With
End Function
End Module
Thanks a lot