Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The following code uses the SendInput function from the Windows API to simulate the <kbd>Control</kbd>-<kbd>C</kbd> key combination, in order to copy the current text selection to the Clipboard. </p> <p>The copy/print subroutine (the very last procedure in the code) calls two utility functions to trigger the necessary key presses and then uses the code you prepared to retrieve the text from the Clipboard. </p> <p>I've tested the code in the Immediate window, the code editor pane, and the worksheet.</p> <pre><code> Option Explicit 'adapted from: ' http://www.mrexcel.com/forum/excel-questions/411552-sendinput-visual-basic-applications.html Const VK_CONTROL = 17 'keycode for Control key Const VK_C = 67 'keycode for "C" Const KEYEVENTF_KEYUP = &amp;H2 Const INPUT_KEYBOARD = 1 Private Type KEYBDINPUT wVK As Integer wScan As Integer dwFlags As Long time As Long dwExtraInfo As Long End Type Private Type GENERALINPUT dwType As Long xi(0 To 23) As Byte End Type Private Declare Function SendInput Lib "user32.dll" _ (ByVal nInputs As Long, _ pInputs As GENERALINPUT, _ ByVal cbSize As Long) As Long Private Declare Sub CopyMemory Lib "kernel32" _ Alias "RtlMoveMemory" _ (pDst As Any, _ pSrc As Any, _ ByVal ByteLen As Long) Private Sub KeyDown(bKey As Byte) Dim GInput(0 To 1) As GENERALINPUT Dim KInput As KEYBDINPUT KInput.wVK = bKey KInput.dwFlags = 0 GInput(0).dwType = INPUT_KEYBOARD CopyMemory GInput(0).xi(0), KInput, Len(KInput) Call SendInput(1, GInput(0), Len(GInput(0))) End Sub Private Sub KeyUp(bKey As Byte) Dim GInput(0 To 1) As GENERALINPUT Dim KInput As KEYBDINPUT KInput.wVK = bKey KInput.dwFlags = KEYEVENTF_KEYUP GInput(0).dwType = INPUT_KEYBOARD CopyMemory GInput(0).xi(0), KInput, Len(KInput) Call SendInput(1, GInput(0), Len(GInput(0))) End Sub Sub CopyToClipboardAndPrint() Dim str As String 'Simulate control-C to copy selection to clipboard KeyDown VK_CONTROL KeyDown VK_C KeyUp VK_C KeyUp VK_CONTROL DoEvents Dim Clip As MSForms.DataObject Set Clip = New MSForms.DataObject Clip.GetFromClipboard Debug.Print Clip.GetText End Sub </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload