Screen Capture VBA

In this example we'll use screen capture VBA to copy the active window to the clipboard and then paste it into a Word document.

We will be using an API - Application Programming Interface - to capture the screen we want. APIs call, or execute, Window's functions. They privide information and can access everything from memory, security, network, windows, registry and more.

To use the API we will use today, we include/declare it at the top of the module. although ours is declared as Private, if you want to access an API from other modules you can declare it with the word Public, instead of the word Private.

In Word, press ALT + F11 to open the VBA editor.

At the upper left, right click on the Module's folder in the VBA Project Explorer and insert a new module. 

Screen Capture VBA


In the following code a message appears. Three seconds after we click its OK button, the code will capture the active window. Prepare what you want to capture, go to Word and run the macro (see instructions on how to create a toolbar button for a macro below)...

After 3 seconds return to Word and click OK on the new message box to paste the captured image.

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 ScreenCapture()
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
Sub Screen_Capture_VBA()
Dim Sec3 As Date, PasteYes As Integer
MsgBox "Three seconds after you click OK " & _
"the active window will be copied to the clipboard."
Sec3 = DateAdd("s", 2, Now)
Do Until Now > Sec3
DoEvents
Loop
ScreenCapture
PasteYes = MsgBox("Click OK to paste the screen capture in VBA.", _
vbOKCancel)
If PasteYes = 1 Then
Selection.Paste
End If
End Sub
How to create a toolbar button for a Screen Capture VBA...

1. Right click on any toolbar button or grey space in the toolbar. A long menu will appear of all the possible toolbars you could add to Word.

2. Click on the word Customize at the bottom.

3. If the Customize dialog box does not display with the middle tab Commands selected to the foreground, click on Commands.

4. Scroll down in the list on the left and select Macros.

5. In the left pane you should now see a list of macros you’ve created. Scroll down and find the row with screen capture VBA.

For more advanced ways of capturing in Visual Basic, not VBA, see the article, "How To Capture and Print the Screen, a Form, or Any Window"

This site is powered by Site Build It!. If you enjoy it, please check out the
Site Build It homepage
 to learn more and on how to build a success-guaranteed site with no technical skills.

Custom Search






Return from Screen Capture VBA to VBA Code Samples

Return to our Home page