'Purpose : Copies the selected items in a listview to the clipboard
'Inputs : lvCopy The listview to copy the selected items from
' [bIncludeHeaders] If True the listview headers are also copied
' [lFirstCol] The first column to copy to the clipboard,
' if not specified copies all columns
' [lLastCol] The last column to copy to the clipboard,
' if not specified copies all columns
'Outputs : Returns the number of items copied on success, else returns -1
Function LvCopyToClipboard(lvCopy As ListView, Optional bIncludeHeaders As Boolean, Optional lFirstCol As Long = 1, Optional lLastCol As Long = -1) As Long
Dim lThisRow As Long, lThisCol As Long, lNumCols As Long
Dim sRow As String, sClipboard As String
On Error GoTo ErrFailed
With lvCopy.ListItems
'Loop over the items in the listview
lNumCols = lvCopy.ColumnHeaders.Count
If lLastCol = -1 Then
lLastCol = lNumCols
End If
If bIncludeHeaders Then
sRow = ""
For lThisCol = lFirstCol To lLastCol
sRow = sRow & (lvCopy.ColumnHeaders.item(lThisCol).Text & vbTab)
Next
sClipboard = sClipboard & (sRow & vbNewLine)
End If
For lThisRow = 1 To .Count
If .item(lThisRow).Selected Then
'Copy the selected item
sRow = ""
sRow = .item(lThisRow).Text
For lThisCol = lFirstCol To lLastCol - 1
sRow = sRow & (vbTab & .item(lThisRow).SubItems(lThisCol))
Next
sClipboard = sClipboard & (sRow & vbNewLine)
LvCopyToClipboard = LvCopyToClipboard + 1
End If
Next
End With
Clipboard.Clear
DoEvents
Clipboard.SetText sClipboard, vbCFText
Exit Function
ErrFailed:
Debug.Print "Error copying to clipboard " & Err.Description
Debug.Assert False
LvCopyToClipboard = -1
End Function