Tuesday, August 20, 2013

Print Userform in Landscape Format


Private Declare Sub keybd_event Lib "user32" _
(ByVal bVk As Byte, _
ByVal bScan As Byte, _
ByVal dwFlags As Long, _
ByVal dwExtraInfo As Long)

'dwFlags parameter of keybd_event controls various aspects of function operation. _

'This parameter can be one or more of the following values.

'KEYEVENTF_KEYUP
'if specified, the key is being released.If not specified, the key is being depressed.

'KEYEVENTF_EXTENDEDKEY
'If specified, the scan code was preceded by a prefix _
'byte having the value 0xE0 (224).

Private Const KEYEVENTF_KEYUP = &H2
Private Const KEYEVENTF_EXTENDEDKEY = &H1
'Print Screen key
Private Const VK_SNAPSHOT = &H2C
'Alt Key
Private Const VK_MENU = &H12
'Left Alt Key
Private Const VK_LMENU = &HA4

Private Sub CommandButton1_Click()
    Dim wshTemp As Worksheet
    DoEvents

    ' Simulate pressing ALT+Printscreen to copy the form window (=picture) to
    ' the clipboard
    keybd_event VK_LMENU, 0, KEYEVENTF_EXTENDEDKEY, 0
    keybd_event VK_SNAPSHOT, 0, KEYEVENTF_EXTENDEDKEY, 0
    keybd_event VK_SNAPSHOT, 0, KEYEVENTF_EXTENDEDKEY + KEYEVENTF_KEYUP, 0
    keybd_event VK_LMENU, 0, KEYEVENTF_EXTENDEDKEY + KEYEVENTF_KEYUP, 0
    DoEvents

    ' Add a worksheet named Temp
    ThisWorkbook.Worksheets.Add
    ActiveSheet.Name = "Temp"
    Set wshTemp = ThisWorkbook.Worksheets("Temp")

    ' Paste the picture, set print orientation to landscape en print it
    With wshTemp
     .Paste
     .PageSetup.Orientation = xlLandscape
     .PrintOut
    End With

    ' Delete the worksheet Temp and suppress the not-saved Warning.
    Application.DisplayAlerts = False
    ThisWorkbook.Worksheets("Temp").Delete
    Application.DisplayAlerts = True
End Sub

No comments:

Post a Comment