Skip to content

Instantly share code, notes, and snippets.

@cristianbuse
Last active May 15, 2023 21:20
Show Gist options
  • Save cristianbuse/a76fb57d1b4227878e27add670bd7ea6 to your computer and use it in GitHub Desktop.
Save cristianbuse/a76fb57d1b4227878e27add670bd7ea6 to your computer and use it in GitHub Desktop.
Sleep API Mac compatible
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
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
Public Declare Sub Sleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
#End If
#End If
#If Mac Then
Public Sub Sleep(ByVal dwMilliseconds As Long)
Const maxMicro As Long = &HFFFFFED8 'unsigned &HFFFFFFFF divided by 1000 is not round
Const maxMilli As Long = &H418937 'unsigned &HFFFFFED8 divided by 1000
Const maxMilliPos As Long = maxMilli \ 2 '&H20C49B
Const signBit As Long = &H80000000
Const maxMilliNeg As Long = maxMilli Or signBit
'
Do While dwMilliseconds And signBit
USleep maxMicro
If dwMilliseconds < maxMilliNeg Then
dwMilliseconds = (dwMilliseconds Xor signBit) - maxMilli Xor signBit
Else
dwMilliseconds = dwMilliseconds - maxMilli
End If
Loop
Do While dwMilliseconds > maxMilli
USleep maxMicro
dwMilliseconds = dwMilliseconds - maxMilli
Loop
If dwMilliseconds > maxMilliPos Then
USleep (dwMilliseconds * 500& Or signBit) * 2&
Else
USleep dwMilliseconds * 1000&
End If
End Sub
#End If
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment