aziz rasul
Active member
- Local time
- Today, 00:21
- Joined
- Jun 26, 2000
- Messages
- 1,935
Does anyone have any VBA code to be used in Excel that loops through say 5 open Access db's and enables me to close a specific one?
Dim appAccess As Object
Dim appAccess2 As Object
Sub Example1()
'Access object
'create new access object
Dim myDir As String
myDir = CurDir
Debug.Print myDir
Set appAccess = CreateObject("Access.Application")
Set appAccess2 = CreateObject("Access.Application")
'open the acces project
appAccess.OpenCurrentDatabase myDir & "\" & "zigzag.accdb"
appAccess.Visible = True
appAccess2.OpenCurrentDatabase myDir & "\" & "zigzag2.accdb"
appAccess2.Visible = True
MsgBox "2 DBs are open. Close the first"
CloseDb appAccess
MsgBox "Close the Second"
CloseDb appAccess2
End Sub
Public Sub CloseDb(TheDb As Object)
TheDb.CloseCurrentDatabase
End Sub
Dim objExcelApp As Object
Dim wb As Excel.Workbook
Set objExcelApp = GetObject(, "Excel.Application")
For Each wb In objExcelApp.Workbooks
If wb.Name = strExcelFile Then
wb.Close True
Exit For
End If
Next wb
If objExcelApp.Workbooks.Count = 0 Then
objExcelApp.Application.Quit
End If
Set objExcelApp = Nothing
My issue is slightly different. I have separate code that opens up different MS Access databases. At one point I now want to close a specific MS Access database. To do that I need to grab the particular instance of the specific MS Access file and close it. One way of doing this, I thought, was to iterate through the open MS Access databases, 'catch' the one I want and close it, much like you do when you iterate through open workbooks e.g.
'Need reference to Microsoft Scripting Runtim
Dim MyDict As Dictionary
Sub Example1()
'create new access object
Dim appAccess As Object
Dim myDir As String
Set MyDict = New Dictionary
myDir = CurDir
Set appAccess = CreateObject("Access.Application")
'open the acces project
appAccess.OpenCurrentDatabase myDir & "\" & "zigzag.accdb"
appAccess.Visible = True
'store in dictionary
MyDict.Add appAccess.currentproject.Name, appAccess
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase myDir & "\" & "zigzag2.accdb"
MyDict.Add appAccess.currentproject.Name, appAccess
appAccess.Visible = True
End Sub
Public Sub CloseDbByName(strName As String)
Dim TheDb As Object
If MyDict.Exists(strName) Then
Set TheDb = MyDict(strName)
MyDict.Remove strName
TheDb.CloseCurrentDatabase
TheDb.Quit
End If
End Sub
' Call the db by name to close it
Public Sub PromptClose()
CloseDbByName "zigzag.accdb"
End Sub
Public Sub PromptClose2()
CloseDbByName "zigzag2.accdb"
End Sub
Dim db as DAO.Database
Dim rs as DAO.Recordset
Set db = Opendatabase("PATH AND FILENAME TO DB.mdb")
Set rs = db.Openrecordset("NAME OF TABLE")
Ah - no mention of this earlier.I am writing code in Excel.