首页 > 解决方案 > 当用户在对话框中写入要删除的条目的名称时,如何删除组合框列表中的特定项目

问题描述

所以我的问题主要在标题中解释,我有一个按钮,按下时会问“你想删除什么?”。然后用户写入要删除的内容并将其从列表中删除。

Sub DeleteShip()

Dim a As Variant
Dim b As String

a = InputBox("Vælg fartøj der skal slettes")
b = CStr(a)

If Sheet1.ShipList.Value = b Then
Sheet1.ShipList.RemoveItem (ShipList.ListIndex(b))
Else
MsgBox "Det skib findes ikke i listen, har du stavet det korrekt?"
End If
End Sub

标签: excelvba

解决方案


试试下面的代码。您可能需要更新ComboBox1.

要查找名称:
- 在设计模式中选择组合框。- 单击格式功能区。
- 在排列部分单击选择窗格
- 所有形状、它们的名称和可见性都将显示在单独的窗格中。

如果您使用范围来填充组合框,这将起作用:

Sub DeleteShp()

    Dim a As String
    Dim rFound As Range
    Dim LookupRange As Range

    Set LookupRange = Range(Sheet1.ComboBox1.ListFillRange)

    a = Trim(InputBox("Vælg fartøj der skal slettes"))

    With LookupRange
        Set rFound = .Find(What:=a, After:=.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext)
        If Not rFound Is Nothing Then
            rFound.Delete Shift:=xlUp
        End If
    End With

End Sub  

如果您使用以下方式填充了组合框AddItem

Sub InitialiseShp()
'Fills combobox with "Item A" to "Item F".
    Dim x As Long

    Sheet1.ComboBox1.Clear

    For x = 65 To 70
        Sheet1.ComboBox1.AddItem "Item " & Chr(x)
    Next x

End Sub

您需要搜索项目以返回要删除的正确索引号:

Sub DeleteShp_2()

    Dim a As String
    Dim x As Long

    a = Trim(InputBox("Vælg fartøj der skal slettes"))

    With Sheet1.ComboBox1
        For x = 0 To .ListCount - 1
            If .List(x) = a Then
                .RemoveItem x
                Exit For
            End If
        Next x
    End With

End Sub

推荐阅读