簡體   English   中英

使用VBA將文本復制到剪貼板

[英]Copying text to clipboard using VBA

在MS Excel 2010中,我嘗試使用SendKeys將一些文本復制到剪貼板。 但是,它不起作用。

微軟為了防止人們創建欺詐性宏而采取了某種安全措施嗎? 這是一些代碼,顯示了我想做的事情(假設您在vba窗口中,並且選擇了一些文本):

Public Sub CopyToClipboardAndPrint()
    Call SendKeys("^(C)", True)
    Dim Clip As MSForms.DataObject
    Set Clip = New MSForms.DataObject
    Clip.GetFromClipboard
    Debug.Print Clip.GetText
End Sub

請注意,為了使用MSForms.DataObject,您必須引用%windir%\\system32\\FM20.DLL (即Microsoft Forms 2.0對象庫)。


編輯:我要復制的文本不在文檔窗口中,而是在vba項目窗口的直接窗口中! 因此Selection.Copy在這里不起作用。

以下代碼使用Windows API中的SendInput函數來模擬Control - C組合鍵,以便將當前的文本選擇復制到剪貼板。

復制/打印子例程(代碼中的最后一個過程)調用兩個實用程序函數來觸發必要的按鍵,然后使用您准備的代碼從剪貼板中檢索文本。

我已經在“即時”窗口,代碼編輯器窗格和工作表中測試了代碼。

  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 = &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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM