该答案应该为您提供一种通用方法,该方法使用互斥锁保护某些共享数据,从而实现Excel-VBA和word-VBA之间的同步。详细信息取决于您的目标应用程序。
想法是这样的,您可以在ThisWorkbookExcel 模块中以及类似地在ThisDocumentWord中创建以下代码:
' 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1268 次 |
| 最近记录: |