GDG Macros Lesson 7: A touch of WinAPI and using keyboard modifier keys

Hi.

Holding a key modifies the fucntion of a macro.

Ie hold shift and run the macro and it does this, hold Crtl and it does this... etc.

A great way to make your macros multi functional.

I also lightly touch base on Option Explicit which makes variable declaration necessary.

I also quickly talk about If, Else, ElseIf conditionals and colors.

Enjoy! (the code is pasted below)

~John

 

Option Explicit

#If VBA7 Then
    Private Declare PtrSafe Function GetAsyncKeyState Lib "user32" (ByVal vKey As LongPtr) As Integer
#Else
    Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
#End If

'Private Const VK_ESCAPE = &H1B
'Private Const VK_RETURN = &HD
Private Const VK_SHIFT = &H10
Private Const VK_CONTROL = &H11

Sub makeRect()

    Dim s As Shape, sRect As Shape
    Dim x As Double, y#, h#, w#
    Dim dMarg#
    Dim col As New Color
   
   
   
   
    If GetAsyncKeyState(VK_SHIFT) Then
        dMarg = 0.25
        col.RGBAssign 255, 0, 0
    ElseIf GetAsyncKeyState(VK_CONTROL) Then
        dMarg = 0.25
        col.RGBAssign 255, 0, 0
    Else
        dMarg = 0.1
        col.RGBAssign 0, 0, 255
    End If
   
    ActiveDocument.Unit = cdrInch
    Set s = ActiveShape
    If s Is Nothing Then Exit Sub
   
    's.GetBoundingBox x, y, w, h
    myGetBoundingBox s, x, y, w, h
   
    Set sRect = ActiveLayer.CreateRectangle2(x - dMarg, y - dMarg, w + (dMarg * 2), h + (dMarg * 2))
    sRect.Fill.UniformColor.CopyAssign col
    sRect.OrderToBack
   
End Sub

Private Function myGetBoundingBox(ByVal s As Shape, ByRef x As Double, y#, w#, h#)
     h = s.SizeHeight
     w = s.SizeWidth
     ActiveDocument.ReferencePoint = cdrBottomLeft
     x = s.PositionX
     y = s.PositionY
End Function