Add Reference Library to an outside MS Access Database - vba

I have a code that creates new MS Access Databases. I'd like to add reference libraries to these newly created MS Access Databases.
Here is the code that I wrote but is not working:
Sub makeDb(fl As String)
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
'check if the file already exists
If fs.FileExists(fl) = False Then
'create new ms access database
Dim accessApp As Access.Application
Set accessApp = New Access.Application
accessApp.DBEngine.CreateDatabase fl, dbLangGeneral
'loop through all references in current database and add them to the newly created dbs
Dim cur_vbProj As VBIDE.VBProject: Set cur_vbProj = Application.VBE.VBProjects(1)
Dim cur_vbRefs As VBIDE.References: Set cur_vbRefs = cur_vbProj.References
Dim cur_vbRef As VBIDE.Reference
For Each cur_vbRef In cur_vbRefs
Dim cur_guid As String: cur_guid = cur_vbRef.Guid
Dim cur_major As Long: cur_major = cur_vbRef.Major
Dim cur_minor As Long: cur_minor = cur_vbRef.Minor
'here is the code that doesn't work
Dim vbProj As VBIDE.VBProject: Set vbProj = accessApp.Application.VBE.VBProjects(1)
Dim vbRefs As VBIDE.References: Set vbRefs = vbProj.References
vbRefs.AddFromGuid Guid:=cur_guid, Major:=cur_major, Minor:=cur_minor
Next
accessApp.Quit
Set accessApp = Nothing
End If
End Sub
The line Set vbProj = accessApp.Application.VBE.VBProjects(1) throws Run-Time error '9' Subscript out of range. How should I modify the code? Is it even possible to add references to an outside database?

Following works for me:
Sub makeDb(f1 As String)
Dim accApp As Access.Application
Dim cur_vbRefs As References
Dim cur_vbRef As Reference
If Dir(f1) = "" Then
Access.DBEngine.CreateDatabase f1, dbLangGeneral
Set accApp = New Access.Application
accApp.OpenCurrentDatabase f1
'loop through all references in current database and add them to the newly created dbs
Set cur_vbRefs = Application.References
For Each cur_vbRef In cur_vbRefs
On Error Resume Next
accApp.References.AddFromGuid cur_vbRef.Guid, cur_vbRef.Major, cur_vbRef.Minor
Next
End If
End Sub

Related

Update function not working in MS Access Userform

Private Sub Command15_Click()
On Error Resume Next
Dim db As Database
Dim RST As Variant
Set db = CurrentDb
Set RST = db.OpenRecordset("SSPTab")
With RST
.Edit
.Fields(6) = Me.Reviewersname
.Fields(9) = Me.Assessments
.Fields(11) = Me.Review_Comments
.Fields(7) = Me.Reviewstatus
.Update
End With
I would like to open the existing row details and make changes to it and update. The above code is working fine for me except .Fields(7) , showing data conversion error.
Use proper declarations:
Private Sub Command15_Click()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Set db = CurrentDb
Set rst = db.OpenRecordset("SSPTab")
With rst
.Edit
.Fields(6).Value = Me!Reviewersname.Value
.Fields(9).Value = Me!Assessments.Value
.Fields(11).Value = Me!Review_Comments.Value
' Field 7 must be Short Text or Long Text.
' .Fields(7).Value = Me!Reviewstatus.Value
.Fields(7).Value = Me!Revstats.Value
.Update
.Close
End With
End Sub

XmlDocument in Outlook VBA

I am trying to adapt this answer, which I believe is in VB.NET, for use with Outlook VBA.
I made some progress by getting the syntax corrected for VBA, but I do not know how to resolve "Compile error: User-defined type not defined" on the line
Dim CurrentXML As XmlDocument
Tool > References includes Microsoft XML, v6.0 but searching for XmlDocument in Object Browser returns no results.
The complete code is as follows:
Sub Search2()
' https://stackoverflow.com/a/50145011/18573
Dim sFilter As String
Dim CurrentExplorer As Outlook.Explorer
Set CurrentExplorer = Nothing
Dim CurrentView As Outlook.View
Set CurrentView = Nothing
' ERROR ON THE FOLLOWING LINE
Dim CurrentXML As XmlDocument
Set CurrentXML = New XmlDocument
Dim CurrentFilterNodes, CurrentViewNodes As XmlNodeList
Dim CurrentFilterNode, CurrentParentNode As XmlNode
sFilter = "urn:schemas:httpmail:subject LIKE '%Build Error%'"
CurrentExplorer = TryCast(ExplorerObj, Outlook.Explorer)
If (CurrentExplorer Is Not Nothing) Then
CurrentView = CurrentExplorer.CurrentView
If (CurrentView Is Not Nothing) Then
CurrentXML.LoadXML (CurrentView.xml)
CurrentFilterNodes = _
CurrentXML.getElementsByTagName("filter")
If CurrentFilterNodes.Count > 0 Then
For y = 0 To CurrentFilterNodes.Count - 1
CurrentFilterNode = CurrentFilterNodes(y)
If CurrentFilterNode.HasChildNodes Then
For i = CurrentFilterNode.ChildNodes.Count - 1 To 0 Step -1
CurrentFilterNode.RemoveChild (CurrentFilterNode.ChildNodes(i))
Next i
End If
Next y
CurrentFilterNode = CurrentFilterNodes(0)
CurrentFilterNode.appendChild ( _
CurrentXML.createTextNode(sFilter))
Else
CurrentViewNodes = CurrentXML.getElementsByTagName("view")
If CurrentViewNodes Is Not Nothing Then
CurrentParentNode = CurrentViewNodes(0)
CurrentFilterNode = CurrentXML.createElement("filter")
CurrentParentNode.appendChild (CurrentFilterNode)
CurrentFilterNode.appendChild (CurrentXML.createTextNode(sFilter))
End If
End If
CurrentView.xml = CurrentXML.InnerXml
CurrentView.Apply
Marshal.ReleaseComObject (CurrentView)
End If
End Sub
The VBA code for Outlook should look like as follows
Option Explicit
Sub Search2()
' https://stackoverflow.com/a/50145011/18573
' Add reference Microsoft XML, v6.0
Dim sFilter As String
Dim oExplorer As Explorer
Dim oView As View
Dim oXML As DOMDocument60
Dim cFilterNodes As IXMLDOMNodeList
Dim cViewNodes As IXMLDOMNodeList
Dim oFilterNode As IXMLDOMNode
Dim oParentNode As IXMLDOMNode
Dim y As Long
Dim i As Long
sFilter = "urn:schemas:httpmail:subject LIKE '%Build Error%'"
Set oXML = New DOMDocument60
Set oExplorer = ActiveExplorer
If Not oExplorer Is Nothing Then
Set oView = oExplorer.CurrentView
If Not oView Is Nothing Then
oXML.LoadXML oView.XML
Set cFilterNodes = oXML.getElementsByTagName("filter")
If cFilterNodes.Length > 0 Then
For y = 0 To cFilterNodes.Length - 1
Set oFilterNode = cFilterNodes(y)
If oFilterNode.HasChildNodes Then
For i = oFilterNode.ChildNodes.Length - 1 To 0 Step -1
oFilterNode.RemoveChild oFilterNode.ChildNodes(i)
Next
End If
Next
Set oFilterNode = cFilterNodes(0)
oFilterNode.appendChild oXML.createTextNode(sFilter)
Else
Set cViewNodes = oXML.getElementsByTagName("view")
If cViewNodes.Length > 0 Then
Set oParentNode = cViewNodes(0)
Set oFilterNode = oXML.createElement("filter")
oParentNode.appendChild oFilterNode
oFilterNode.appendChild oXML.createTextNode(sFilter)
End If
End If
Else
Set cViewNodes = oXML.getElementsByTagName("view")
If cViewNodes.Length > 0 Then
Set oParentNode = cViewNodes(0)
Set oFilterNode = oXML.createElement("filter")
oParentNode.appendChild oFilterNode
oFilterNode.appendChild oXML.createTextNode(sFilter)
End If
End If
oView.XML = oXML.XML
oView.Apply
End If
End Sub

How do I prevent .Run in Outlook from opening an Access instance twice?

In MS Outlook I have a button that calls a macro in MS Access. That macro opens a form and sets a text. Everytime if I push that button a new instance of Access is being opened. How do I prevent opening multiple instances of Access?
Outlook code:
'general declarations:
Public appAccess As Object
Sub OpenRecord()
Dim Reference As String
Dim docAccess
Reference = 'teststring'
Set appAccess = CreateObject("Access.Application")
docAccess = appAccess.opencurrentdatabase("D:\Database\MSA_db.accdb")
appAccess.Visible = True
appAccess.Run "OpenInternalReference", Reference
End Sub
Access Code:
Public Sub OpenInternalReference(MailReference As String)
Dim stDocName As String
Dim stLinkCriteria As String
stDocName = "browse"
DoCmd.OpenForm stDocName, , , stLinkCriteria
Forms("Browse").prefilter.SetFocus
Forms("Browse").prefilter.Text = MailReference
End Sub
Your problem is not the .Run method, it is your Set appAccess = CreateObject("Access.Application") since it always creates a new instance of access.
This code tries to get an Access Application that is already opened and creates a new if none is found:
Dim appAccess As Object
On Error Resume Next
Set appAccess = GetObject(Class:="Access.Application")
On Error GoTo 0
If appAccess Is Nothing Then
Set appAccess = CreateObject("Access.Application")
End If

NullReferenceException was unhandled by user code - declaring Excel.Worksheet object

I'm transitioning from Excel VBA to VB.NET, so if this is a dumb question, please go easy on me. I get a NullReferenceException was unhandled by user code on this line of the following sub:
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
VS says that the Object reference is not set to an instance of the object. I'm not sure why it's asking for that, because I've already declared a new instance of Excel in the objApp variable. Why would I need to declare a new instance of each object under that class? It's very possible I'm not thinking about that correctly, but I just wanted to mention my thoughts. Overall, I'm just trying to test the sub below to see if it will open and close a connection to a PostgreSQL database.
Imports Microsoft.Office.Interop
Public Sub QueryData(ByVal ribbonUI As Office.IRibbonControl)
Dim objApp As New Excel.Application
Dim objBook As Excel.Workbook = objApp.ActiveWorkbook
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
Dim pgconn As String
pgconn = "Driver={PostgreSQL};" &
"Server = localhost;" &
"Port = 5432;" &
"Database = CFABudget;" &
"Uid = postgres;" &
"Pwd = budgeto;"
Dim SQL As String = objSheet.Range("BudgetSQL").Text
Dim conn As New Data.Odbc.OdbcConnection(pgconn)
Dim cmd As Data.Odbc.OdbcCommand = New Data.Odbc.OdbcCommand(SQL)
conn.Open()
MsgBox("Success!", vbOKOnly)
conn.Close()
End Sub
Thank you all for your help!
Replace
Dim objApp As New Excel.Application
With:
Dim objApp As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
You were trying to get active workbook from new empty instance of excel.

Update sql database using Lotusscript

I am trying to update rows of my database through lotusscript. My database connection working well. But the result.update command doesn't work and my rows aren't updated by the query. The problem is in the query result.updaterow because it doesn't make errors anywhere else.
Anyone have a solution to make it work;
Option Public
Option Declare
UseLSX "*LSXODBC"
Sub Initialize
Dim session As New NotesSession
Dim db As NotesDatabase
Dim dbcontacts As NotesDatabase
Dim doc As NotesDocument
Dim DocContact As NotesDocument
Dim CandidatView As NotesView
Dim ContactView As NotesView
Dim connection As ODBCConnection
Dim query As ODBCQuery
Dim result As ODBCResultSet
Dim consultantref As String
Set db = session.CurrentDatabase
Set connection = New ODBCConnection
Set dbcontacts= session.GetDatabase("", "names.nsf")
Set query = New ODBCQuery
Set result = New ODBCResultSet
Set query.Connection = connection
Set result.Query = query
On Error Resume Next
Set CandidatView=db.GetView( "Persons" )
Set ContactView=dbcontacts.GetView( "(PersonsTestImport)" )
Call connection.ConnectTo("datasource", "username", "password")
If connection.IsConnected Then
Set doc=CandidatView.GetFirstDocument
CandidatView.AutoUpdate = False
While Not ( doc Is Nothing )
query.SQL="select * from users where id_toucan='"+doc.can_doc_ID(0)+"'"
result.Execute
If result.IsResultSetAvailable Then
Do
result.NextRow
namepers=doc.can_pers(0)
Set DocContact=ContactView.Getdocumentbykey(consultantref)
Call result.SetValue("first_name",DocContact.FirstName(0))
Call result.SetValue("last_name", DocContact.LastName(0))
Call result.SetValue("email", DocContact.MailAddress(0))
result.UpdateRow
Loop Until result.IsEndOfData
End If
Set doc = CandidatView.GetNextDocument( doc )
Wend
Else
MsgBox"Not connected"
End If
result.Close(DB_CLOSE)
connection.Disconnect
End Sub
I tried it with the sql query UPDATE and it's working now :
Option Public
Option Declare
UseLSX "*LSXODBC"
Sub Initialize
Dim session As New NotesSession
Dim db As NotesDatabase
Dim dbcontacts As NotesDatabase
Dim doc As NotesDocument
Dim DocContact As NotesDocument
Dim CandidatView As NotesView
Dim ContactView As NotesView
Dim connection As ODBCConnection
Dim query As ODBCQuery
Dim result As ODBCResultSet
Dim consultantref As String
Set db = session.CurrentDatabase
Set connection = New ODBCConnection
Set dbcontacts= session.GetDatabase("", "names.nsf")
Set query = New ODBCQuery
Set result = New ODBCResultSet
Set query.Connection = connection
Set result.Query = query
On Error Resume Next
Set CandidatView=db.GetView( "Persons" )
Set ContactView=dbcontacts.GetView( "(PersonsTestImport)" )
Call connection.ConnectTo("datasource", "username", "password")
If connection.IsConnected Then
Set doc=CandidatView.GetFirstDocument
CandidatView.AutoUpdate = False
While Not ( doc Is Nothing )
namepers=doc.can_pers(0)
Set DocContact=ContactView.Getdocumentbykey(consultantref)
Set DocContact=ContactView.Getdocumentbykey(consultantref)
first_name_ref=DocContact.FirstName(0)
last_name_ref=DocContact.LastName(0)
email_ref=DocContact.MailAddress(0)
query.SQL="UPDATE users SET email_consult_ref='"+email_ref+"', first_name_consult_ref='"+first_name_ref+"',last_name_consult_ref='"+last_name_ref+"' where id_toucan='"+doc.can_doc_ID(0)+"'"
result.Execute
If result.IsResultSetAvailable Then
Do
result.NextRow
Loop Until result.IsEndOfData
End If
Set doc = CandidatView.GetNextDocument( doc )
Wend
End If
result.Close(DB_CLOSE)
connection.Disconnect
End Sub