首页 > 解决方案 > Excel VBA中mac的睡眠等效项

问题描述

我想在 Excel 的 macOS VBA 编辑器中添加 500 毫秒的等待块。我知道

Application.Wait (Now + TimeValue("0:00:01"))

有效,但这不能低于 1 秒。我也尝试过 sleep 命令:

Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
...
Sleep 500 

但这给了我一个错误说

File Not Found "kernel32" 

有什么办法可以做到这一点?

标签: excelvbamacos

解决方案


这适用于 Windows 和 Mac:

Option Explicit

#If Mac Then
    #If VBA7 Then
        Public Declare PtrSafe Sub USleep Lib "/usr/lib/libc.dylib" Alias "usleep" (ByVal dwMicroseconds As Long)
    #Else
        Public Declare Sub USleep Lib "/usr/lib/libc.dylib" Alias "usleep" (ByVal dwMicroseconds As Long)
    #End If
#Else 'Windows
    #If VBA7 Then
        Private Declare PtrSafe Sub MSleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
    #Else
        Private Declare  Sub MSleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
    #End If
#End If

Public Sub Sleep(ByVal dwMilliseconds As Long)
#If Mac Then
    USleep dwMilliseconds * 1000&
#Else
    MSleep dwMilliseconds
#End If
End Sub

推荐阅读