我正在使用 Word
和 Excel
VBA 进行一些交织的剪贴板魔法,我认为剪贴板作为共享资源可能应该由一个简单的互斥锁来保护。
我将如何在 VBA 中创建和释放命名互斥体?我找不到任何与 VBA 相关的内容。就好像没有人从 VBA 创建过互斥体一样。这不可能吗?
最佳答案
这个答案应该为您提供使用互斥锁来保护某些共享数据来实现 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
关于vba - 在 VBA 中创建和使用命名互斥体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33378100/