否则打开新数据库

否则打开新数据库

本文介绍了通过VBA使用现有数据库(如果已打开),否则打开新数据库,然后在关闭后关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,如果有的话,它将使用一个已经打开的Access数据库,如果没有,它将使用一个新的Access实例.一切正常.

I have the below code which will use an already open Access database if it's there, if not it will use a new Access instance. This is working fine.

Sub DoStuff()
Dim AccApp As Application
Set AccApp = GetObject("C:\DatabaseName.accdb")
--Do Something e.g.
Debug.Print AccApp.CurrentDb.Name
Set AccApp = Nothing
End Sub

此后,我想做的就是让数据库保持打开状态(如果数据库已经打开),但如果不是开始数据库则关闭它.我怎么知道它是否开始.

What I want to do after this is to leave the database open if it was already open but close it if it wasn't to start with. How can I tell whether it was there or not to start with.

我不想测试laccdb文件,因为这些文件在Access意外关闭后仍会保留.

I don't want to test for laccdb files as these can remain after Access closing unexpectedly.

最受赞赏的任何想法.

推荐答案

我设法撬起了我用于其他目的的另一个功能,以解决此问题:

I managed to crowbar another function I had for another purpose into this which solves the issue:

Function bDatabaseOpen(strDBPath As String) As Boolean
Dim objWMIService As Object, colProcessList As Object, objProcess As Object

bDatabaseOpen = False

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'MSACCESS.EXE'")

For Each objProcess In colProcessList
If Not (IsNull(objProcess.commandline)) Then
    If objProcess.commandline Like "*" & strDBPath & "*" Then
        bDatabaseOpen = True
    End If
End If
Next

Set objProcess = Nothing
Set objWMIService = Nothing
Set colProcessList = Nothing
End Function

我可以在调用原始代码之前进行测试(如果它已经打开),然后再对其进行适当处理.

I can test prior to calling my original code if it's already open and then afterwards deal with it appropriately.

这篇关于通过VBA使用现有数据库(如果已打开),否则打开新数据库,然后在关闭后关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:35