Access/VBA Library

CopyStringToClipboard

Copies the specified string to the clipboard.

Syntax

CopyStringToClipboard( stringToCopy )
Parameters
Name Type Description
stringToCopy String Required. String to be copied to the clipboard.
Code
Sub CopyStringToClipboard(stringToCopy As String)
    Dim hGM As Long ' handle Global Memory
    Dim fpGM As Long ' far pointer Global Memory
    
    ' Allocate memory and save the string with termination char
    hGM = GlobalAlloc(GHND, Len(stringToCopy) + 1)
    fpGM = GlobalLock(hGM)
    fpGM = lstrcpy(fpGM, stringToCopy)
    If GlobalUnlock(hGM) <> 0 Then
        Err.Raise vbObjectError, , "Memory could not be allocated"
    End If
    ' Access the Clipboard
    If OpenClipboard(0&) Then
        Call EmptyClipboard
        Call SetClipboardData(CF_TEXT, hGM)
        Call CloseClipboard
    Else
        Err.Raise vbObjectError, , "Clipboard could not be opened"
    End If
End Sub

Remarks

  • An error will be raised when memory allocation fails or the clipboard could not be openend.

See also

  • CloseClipboard
  • EmptyClipboard
  • GlobalAlloc
  • GlobalLock
  • GlobalUnlock
  • OpenClipboard
  • SetClipboardData