D
Deleted member 147267
Guest
Looking for verification here.
I have been trying to help someone elsewhere with automation from Excel whereby the code opens a db and previews a report. Not too difficult it seems, until one raises the prospect that the particular db is already open. In searching this, I found lots of code examples - some dependent on it being in the Access side. Lots of it is gargantuan procedures using APIs of all sorts. I thought there had to be a simpler way, and came up with this:
From my limited testing it seems to work and figuring out if a db is open is only about 4 lines of code. Thus I'm looking for comments and verification on the truth of that, which is why I didn't post this in the repository. I could be way out to lunch given how complicated others seem to have made this. Remember that this for the Excel side of things. I would not have expected that to be important, but using non-API code developed for Access didn't seem to work from Excel (yes, the proper references were set). Granted, I did learn from this that simply omitting the comma (,) in GetObject changes everything, so theirs might have been faulty in some way.
If this should be posted in the repository after it has been vetted, then maybe it should be a much more condensed post. Comments?
I have been trying to help someone elsewhere with automation from Excel whereby the code opens a db and previews a report. Not too difficult it seems, until one raises the prospect that the particular db is already open. In searching this, I found lots of code examples - some dependent on it being in the Access side. Lots of it is gargantuan procedures using APIs of all sorts. I thought there had to be a simpler way, and came up with this:
Code:
OPTION EXPLICIT
Dim objAcc As New Access.Application
Code:
Function testDbReport()
On Error Resume Next
Set objAcc = GetObject(, "Access.Application")
'if err = 0 Access is running, so is the target db open?
If Err.Number = 0 Then
If objAcc.CurrentDb.Name = "complete path here" Then
MsgBox "The specified database is already open. You must close it and try again."
End If
ElseIf Err.Number <> 0 Then 'if err, then Access was not open so load the db
On Error GoTo ErrHandler
With objAcc
.OpenCurrentDatabase "complete path here"
.Visible = True
.DoCmd.OpenReport "rptReportName", acViewPreview
End With
End If
exitHere:
Set objAcc = Nothing
Exit Function
ErrHandler:
If Err <> 2501 Then '2501 = the open report action was cancelled
MsgBox Err.Description, vbExclamation
End If
Resume exitHere
End Function
If this should be posted in the repository after it has been vetted, then maybe it should be a much more condensed post. Comments?