Operacje na ListBox w Excel w VBA

Jak dodać lub usunąć konkretną pozycję w ListBox w Excel VBA? Jak wyczyścić całą listę?

' Replace ListboxName with your Listbox name
' For this example Listbox is placed inside of sheet
' At properties of Listbox add 2 columns

' --- ADD -----------------------------------------------------------
Private Sub AddValue_toListBox()

Dim ListboxLastRecord, i  As Long

    With ThisWorkbook.Sheets("SheetName")
    
        For i = 0 To 2
            .Select
            ListboxLastRecord = .ListboxName.ListCount
            .ListboxName.AddItem
            .ListboxName.List(ListboxLastRecord, 0) = i & "c1"
            .ListboxName.List(ListboxLastRecord, 1) = i & "c2"
        Next i
    End With

End Sub

' --- CLEAR -----------------------------------------------------------
Private Sub ListboxClear()

    With ThisWorkbook.Sheets("SheetName")
        .ListboxName.Clear
    End With

End Sub

' ---REMOVE -----------------------------------------------------------
Private Sub RemoveValue_fromListbox()

Dim ListboxCounter As Long
Dim Value_tobe_Removed

Value_tobe_Removed = "1c2"

With ThisWorkbook.Sheets("SheetName")

    For ListboxCounter = 0 To .ListboxName.ListCount - 1
        
        If ListboxCounter > .ListboxName.ListCount - 1 Then
            Exit For
        End If
    
        If .ListboxName.List(ListboxCounter, 1) = Value_tobe_Removed Then
            .ListboxName.RemoveItem ListboxCounter
            ListboxCounter = ListboxCounter - 1
        End If
    
    Next ListboxCounter

End With

End Sub

 

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *

Witryna wykorzystuje Akismet, aby ograniczyć spam. Dowiedz się więcej jak przetwarzane są dane komentarzy.