在VBA中创建并使用命名的互斥锁

时间:2015-10-27 20:43:18

标签: vba excel-vba word-vba excel

我正在使用WordExcel VBA进行一些交织在一起的剪贴板魔术,我认为剪贴板是一个共享资源应该由一个简单的互斥锁保护。

我如何在VBA中创建和发布已命名的互斥锁?我找不到任何与VBA相关的东西。好像没有人从VBA创建过互斥锁。这不可能吗?

1 个答案:

答案 0 :(得分:4)

此答案应为您提供使用互斥锁实现Excel-VBA与word-VBA之间同步以保护某些共享数据的一般方法。详细信息取决于您的目标应用程序..

这个想法是这样的,您可以在Excel的模块ThisWorkbook中创建此代码,并在Word的ThisDocument中类似地创建:

' Module ThisWorkbook or similarly ThisDocument

Private myMutex As Long

Private Const ERROR_ALREADY_EXISTS = 183&
Private Const MUTEX_ALL_ACCESS = &H1F0001

Private Declare PtrSafe Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (ByVal lpMutexAttributes As Long, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
Private Declare PtrSafe Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare PtrSafe Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare PtrSafe Function OpenMutex Lib "kernel32" Alias "OpenMutexA" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal lpName As String) As Long
Private Declare PtrSafe Function ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) As Long

Private Sub Workbook_Open()
    myMutex = CreateMutex(0, 1, "myMutex")
    Dim er As Long: er = Err.LastDllError
    If er = 0 Then
        MsgBox "myMutex Created"
    ElseIf er = ERROR_ALREADY_EXISTS Then
        MsgBox "mutex previously created"
        myMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, "myMutex")
    Else
        MsgBox "mutex creation failed"
    End If
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    CloseHandle myMutex
End Sub

Private Sub doSomeCriticalTask()
    WaitForSingleObject myMutex, 20000 ' say we can wait for 20 seconds
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' do critical section code, access shared data safely
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ReleaseMutex myMutex
End Sub