How to do a screen capture using VBA

Or: How to invoke the print screen command

Article contributed by Lutz Gentkow

Using SendKeys

Unfortunately, you can't invoke the print screen command directly – SendKeys "{PrtSc}" is not supported in VBA. But as it so frequently does, like a knight in shining armour, WordBasic rides the rescue:

Sub PrintScreen()
    WordBasic.SendKeys "{1068}"
End Sub

(For some strange reason, SendKeys "{1068}" does not work).

The above code works internationally, but if you don't mind your code being language-specific, then for English versions of Word you can use:.

Sub PrintScreen()
    WordBasic.SendKeys "{prtsc}"
End Sub

for German versions of Word you can use:

Sub PrintScreen()
    WordBasic.SendKeys "{druck}"
End Sub

And so on. (Oddly enough, SendKeys "{prtsc}", etc. did not work in Word 6/95; you had to use the keyboard code in those days; so why it should work with the WordBasic object in Word VBA is a mystery).

In the case of the German version, but for some strange reason, not the English or international (1068) versions, you can also use this method to screen capture the active Window (equivalent to pressing Alt + PrtSc) by preceding the SendKeys string with %, as follows:

Sub PrintScreen()
    WordBasic.SendKeys "%{druck}"
End Sub

Note that this is case sensitive; druck must be lower case (otherwise it will be treated as Shift + druck)

Using API calls

Most serious programmers try to avoid using SendKeys if they can, because it has a reputation for unreliability. If you would prefer to avoid using SendKeys, or if you are not using a German version of Word but want to be able to capture the active Window, you can use API calls to capture either the screen or the current window, as follows. The following code sample is a much simplified version of the code posted in Microsoft Knowledge Base article Q240653:

To capture the screen

Option Explicit

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

Private Const VK_SNAPSHOT = &H2C

Sub PrintScreen()
    keybd_event VK_SNAPSHOT, 1, 0, 0
End Sub

To capture the active window

Option Explicit

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

Private Const KEYEVENTF_KEYUP = &H2
Private Const VK_SNAPSHOT = &H2C
Private Const VK_MENU = &H12

Sub AltPrintScreen()
    keybd_event VK_MENU, 0, 0, 0
    keybd_event VK_SNAPSHOT, 0, 0, 0
    keybd_event VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0
    keybd_event VK_MENU, 0, KEYEVENTF_KEYUP, 0
End Sub


Click to view Terms of Use page

Click to view Disclaimer page