如何实现ListBox勾选/取消勾选时自动添加与删除行?
实现ListBox勾选状态自动添加/删除Excel行
原代码仅清空单元格内容并重新写入,未实现真正的行添加/删除功能。以下是修改后的代码,可根据ListBox勾选状态自动增删行:
Sub Rectangle5_Click() Dim xSelShp As Shape, I As Integer Dim xRow As Integer, lastRow As Integer Set xSelShp = ActiveSheet.Shapes(Application.Caller) Set xLstBox = ActiveSheet.ListBox1 If xLstBox.Visible = False Then xLstBox.Visible = True xSelShp.TextFrame2.TextRange.Characters.Text = "OPEN LIST" Else xLstBox.Visible = False xSelShp.TextFrame2.TextRange.Characters.Text = "UPDATE" ' 删除C21及以下的旧行 lastRow = ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Row If lastRow >= 21 Then Rows("21:" & lastRow).Delete Shift:=xlUp End If xRow = 21 ' 遍历勾选项,插入新行并写入内容 For I = 0 To xLstBox.ListCount - 1 If xLstBox.Selected(I) = True Then Rows(xRow).Insert Shift:=xlDown Cells(xRow, 3).Value = "Removal of Existing " & xLstBox.List(I) xRow = xRow + 1 End If Next I End If End Sub
关键改动说明
- 删除旧行:先获取C列最后一行的行号,若该行号≥21,则删除从21行到最后一行的所有行,彻底清除之前的内容行。
- 插入新行:每遇到一个勾选的ListBox项目,就在当前行插入新行,再写入对应内容,确保勾选一个项目就新增一行。
- 行号维护:插入行后自动递增行号,保证内容按勾选顺序依次排列。
内容的提问来源于stack exchange,提问作者Jhoverence Oigoan
相关产品推荐
相关产品推荐

