21 | 08 | 2017

Copy Listview Row(s) to Excel or Word through the Clipboard

It's possible to copy one or more rows in a listview and add them to the clipboard. After that the values can be paste into word or excel with the column structure still in tact. To do so create a form including a listview  and add the code below. 

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        For i = 0 To 20

            ListView1.Items.Add("Line " & i)
            ListView1.Items(i).SubItems.Add("Subitem " & i & " -1")
            ListView1.Items(i).SubItems.Add("Subitem " & i & " -2")
            ListView1.Items(i).SubItems.Add("Subitem " & i & " -3")
            ListView1.Items(i).SubItems.Add("Subitem " & i & " -4")

        Next i

    End Sub

    Private Sub ListView1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles ListView1.KeyDown

        ' First check if CTRL-V is pressed. If so then continue
        If (e.KeyCode = Keys.C AndAlso e.Modifiers = Keys.Control) Then

            Dim i%, j%, strText$

            Clipboard.Clear() ' empty the clipboard
            With ListView1 'cycle the listview rows to see if items are selected
                For i = 0 To .Items.Count - 1
                    If .Items(i).Selected = True Then ' if selected then add to a text string
                        strText = strText & .Items(i).Text
                        For j = 0 To .Items(i).SubItems.Count - 1
                            strText = strText + Chr(9) + .Items(i).SubItems(j).Text
                            'the CHR(9) character is a TAB key. This is used to create columns in Excel. 
                        Next j
                        strText = strText & vbNewLine
                    End If
                Next i
            End With
            Clipboard.SetText(strText) ' Copy the string into the clipboard
            MsgBox("Row(s) succesfully copied into the clipboard" & vbCr & "Now open Excel or Word to paste these values.", vbInformation)

        End If

    End Sub


End Class

The listview should look like this:

ListViewrowstoclipboard

 

 

Select a few rows and hit CTRL-C to copy the selected items to the clipboard.

When you open Excel and hit CTRL-V or Paste the result should look like this:

SampleExcelPaste



Login

Sign up now and upload your code to the website.

Help us to continue.....
Statistics
Articles View Hits
2330621
Latest Articles