Add data to listview VBA

How to fill listview control with data from worksheet, delete data from list view control and transfer data from list-view into text boxes with VBA. Watch the video below:

//secureservercdn.net/160.153.138.177/z98.4d8.myftpupload.com/wp-content/uploads/2017/12/Fill-ListView-Control-with-Data-from-Worksheet.mp4

Watch this video on YouTube.

Heres the complete macro or VBA code to fill a listview control with data from worksheet and how to manipulate the data in the list-view:

Private Sub cmdClose_Click[]
Unload Me
End Sub

Private Sub cmdDelete_Click[]
ListView1.ListItems.Remove [ListView1.SelectedItem.Index]
End Sub

Private Sub cmdSearch_Click[]
Dim itmx As listItem
Set itmx = ListView1.FindItem[TextBox1.Text, lvwText, , lvwPartial]
If itmx Is Nothing Then
MsgBox Record not found!, vbCritical
Else
ListView1.ListItems[itmx.Index].Selected = True
ListView1.SetFocus
End If

Dim myindex As Integer
TextBox1.Text = Me.ListView1.SelectedItem
myindex = Me.ListView1.SelectedItem.Index
TextBox2.Text = Me.ListView1.ListItems.Item[myindex].SubItems[1]
TextBox3.Text = Me.ListView1.ListItems.Item[myindex].SubItems[2]
TextBox4.Text = Me.ListView1.ListItems.Item[myindex].SubItems[3]
End Sub

Private Sub ListView1_BeforeLabelEdit[Cancel As Integer]

End Sub

Private Sub UserForm_Activate[]
With Me.ListView1
.HideColumnHeaders = False
.View = lvwReport
End With

Now we declare the variables
Dim wksh As Worksheet
Dim rngData As Range
Dim rngCell As Range
Dim listItem As listItem
Dim rowCount As Long
Dim colCount As Long
Dim i As Long
Dim j As Long

Set wksh = Worksheets[Sheet1]

Set rngData = wksh.Range[A1].CurrentRegion

Add column headers
For Each rngCell In rngData.Rows[1].Cells
Me.ListView1.ColumnHeaders.Add Text:=rngCell.Value, Width:=100
Next rngCell

Count number of rows in source range
rowCount = rngData.Rows.Count

Count number of columns in source range
colCount = rngData.Columns.Count

Now we fill our ListView
For i = 2 To rowCount
Set listItem = Me.ListView1.ListItems.Add[Text:=rngData[i, 1].Value]
For j = 2 To colCount
listItem.ListSubItems.Add Text:=rngData[i, j].Value
Next j
Next i
End Sub

Further reading:

Export ListView to Excel Spreadsheet

ListView

Video liên quan

Chủ Đề