0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AccessのVBAで別ユーザーが同じAccessファイルを開いているか判定(複数人同時使用防止)

Last updated at Posted at 2023-07-01

やり方

『Microsoft ActiveX Data Objects 2.8 Library』を参照設定に追加。
image.png

サンプル
'フォームを開いた時の動作。
Private Sub Form_Open(Cancel As Integer)
    
    Dim cnn_ As ADODB.Connection
    Set cnn_ = CurrentProject.Connection
    
    Dim rst_ As New ADODB.Recordset
    Set rst_ = cnn_.OpenSchema( _
            adSchemaProviderSpecific _
            , _
            , _
            "{947bb102-5d43-11d1-bdbf-00c04fb92675}" _
        )
    
    'このAccessファイルに接続しているユーザー情報走査。
    Do Until rst_.EOF
    
        'PC名取得。
        Dim using_pc_name_ As String
        using_pc_name_ = Nz(rst_.Fields(0).Value, "")
        using_pc_name_ = Replace(using_pc_name_, " ", "")
        using_pc_name_ = Replace(using_pc_name_, Chr(0), "") 'NULL終端文字列除去。
    
        '接続中PC名が自分のPCと不一致なら、別の誰かが開いているという判定。
        If using_pc_name_ <> Environ("COMPUTERNAME") Then
            MsgBox using_pc_name_ & "がすでにこのAccessファイルを開いています。", vbExclamation
        End If
        
    rst_.MoveNext: Loop
    rst_.Close
    
End Sub
  • Accessファイルを開いている奴の情報はテーブルから取得できる。
  • 上記の情報について、コンピューター名にはスペースやNULL終端文字列が付いているので、除去が必要。

蛇足

『同時使用禁止』とか『誰かが開いている』というエラー文言だけだと、「じゃあ誰が使ってるか調べて」という面倒くさい頼み事に発展することがある。

どのPCが使っているか をユーザーに見せてあげることで、それが回避できると思う。

複数人同時使用禁止が必要な場面

参考サイトさん

バージョン

Windows 10 Pro 22H2 19045.3155
Microsoft Access for Microsoft 365 MSO (バージョン 2305 ビルド 16.0.16501.20074) 32 ビット

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?