excel - 在excel中链接列表框和工作表以进行删除-VBA

标签 excel vba listbox userform

我使用 VBA 用户窗体在 excel 中创建列表框。它的值是从 Excel 中的工作表中获得的。
如何在删除框列表项时删除工作表“数据库”中的值?
请帮我。

Private Sub UserForm_Initialize()
Dim ws      As Worksheet
Dim rng     As Range

Dim MyArray 
Set ws = Sheets("Database")

Set rng = ws.Range("K2:L" & ws.Range("K" & ws.Rows.Count).End(xlUp).Row)

With Me.ListBox1
.Clear
.ColumnHeads = False
.ColumnCount = rng.Columns.Count

 MyArray = rng

.List = MyArray

.ColumnWidths = "90;90"
.TopIndex = 0
End With
End Sub

Private Sub CommandButton2_Click()
For lItem = Me.ListBox1.ListCount - 1 To 0 Step -1
    If ListBox1.Selected(lItem) Then
        ListBox1.RemoveItem lItem
        If Me.ListBox1.MultiSelect = fmMultiSelectSingle Then
            Exit For
        End If
    End If
Next
End Sub

最佳答案

如何删除工作表“数据库”中的值?

当您通过数组方法(不使用 ControlSource )分配数据库项目时,您想知道在手动删除后如何将列表框项目与数据库同步。

方法 A) - 写下整个 Listbox1.List

如果您想要 For 之后的列表框项目的镜像- Next循环,您可以简单地将这些项目写回给定范围(当然,您也应该清除“剩余行”)通过以下一个衬垫

    rng.Resize(Me.ListBox1.ListCount, 2) = Me.ListBox1.List

而不是在 CommandButton2_Click 中重复数据范围声明,我建议在 Userform 代码模块的声明头中声明一次(和 省略 它在 Userform_Initialize 中):

因此完整的代码如下:

Additional notes due to comment



上插入这两行代码顶部 您的用户窗体代码模块(和 之前的 任何程序)。
Option Explicit强烈建议在任何代码中强制声明变量类型(但您不能像以前那样在 Sub 中使用此语句)。声明Dim rng As Range在其他过程之外(即在顶部)允许此代码模块中的任何过程知道 rng多变的。
Option Explicit               ' declaration head of the UserForm module
Dim rng as Range              ' ONE database declaration only!
                              ' << OUTSIDE of following procedures 
' << Start of regular procedures                              
Private Sub UserForm_Initialize()
Dim ws      As Worksheet
' Dim rng   As Range    ' << not needed here, see top declaration
Dim MyArray
Set ws = Sheets("Database")
Set rng = ws.Range("K2:L" & ws.Range("K" & ws.Rows.Count).End(xlUp).Row)
With Me.ListBox1
    .Clear
    .ColumnHeads = False
    .ColumnCount = rng.Columns.Count

     MyArray = rng

    .List = MyArray
    .ColumnWidths = "90;90"
    .TopIndex = 0
End With
End Sub

Private Sub CommandButton3_Click()   
Dim lItem&
For lItem = Me.ListBox1.ListCount - 1 To 0 Step -1
    If ListBox1.Selected(lItem) Then
        ListBox1.RemoveItem lItem           ' remove item from listbox
        If Me.ListBox1.MultiSelect = fmMultiSelectSingle Then
            Exit For
        End If
    End If
Next

rng.Offset(Me.ListBox1.ListCount, 0).Resize(rng.Rows.Count, 2) = "" ' clear rows
rng.Resize(Me.ListBox1.ListCount, 2) = Me.ListBox1.List             ' write list back

End Sub

请注意,不会物理删除任何行,两个目标列中的结果列表框项K:L仅向上移动(方法 B 也允许删除整行)。

方法 B) - 主循环中的帮助程序

在 UserForm 的声明头中使用相同的数据范围声明 ► 如上所示(即在作为 Subs 或 Functions 的过程之外),您可以使用帮助过程 DelData允许区分两种主要情况:
  • [1] 上移数据库中已删除的单元格
  • [2] 删除整行

  • 事件流程 CommandButton2_Click
    Private Sub CommandButton2_Click()
    ' Purpose: delete items both from database and listbox
    Dim lItem&
    For lItem = Me.ListBox1.ListCount - 1 To 0 Step -1
        If ListBox1.Selected(lItem) Then
            DelData lItem, True     ' [1] True=delete items and shift up
           'DelData lItem, False    ' [2] False=delete entire row
    
            ListBox1.RemoveItem lItem           ' remove item from listbox
            If Me.ListBox1.MultiSelect = fmMultiSelectSingle Then
               Exit For                ' do it once in single select case
            End If
        End If
    Next
    End Sub
    

    帮助程序DelData
    Sub DelData(ByVal indx&, Optional ByVal bShiftUp As Boolean = True)
    ' Purpose: delete indicated row items in database
    ' Note:    data set in OP includes header
        If bShiftUp Then    ' [1] bShiftUp = True: delete row items and shift up
           rng.Offset(indx).Resize(1, rng.Columns.Count).Delete xlShiftUp
        Else                ' [2] bShiftUp = False: delete entire row of indicated items
           rng.Offset(indx).Resize(1, rng.Columns.Count).EntireRow.Delete
        End If
    End Sub
    

    旁注

    建议完全限定范围引用以避免从错误的工作簿中获取数据,因此我建议在您的 UserForm_Initialize 中使用以下语句程序:
    Set ws = ThisWorkbook.Worksheets("Database")
    好好享受 :-)

    关于excel - 在excel中链接列表框和工作表以进行删除-VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631755/

    相关文章:

    vba - 使用 .resize() 后将文本存储在变体中

    excel - 如何记录单元格位置(非空)并为每个单元格运行宏

    excel - 检查 Excel 工作簿是否已从另一个 Office 2010 应用程序打开

    vba - Excel VBA ActiveX 列表框不允许单击

    c# - 如果在列表框中选择了 X 个以上的项目,则恢复到之前的选择

    vba - 编写此 Excel VBA 的常规方法是什么?

    java - 无法使用java替换excel文件中的日期

    vba - 为什么 VBA 中的 GetValue 函数使用单元格 "A1"?

    vba - 第一个 VBA 代码 : Run-time Error "1004"

    c# - 带有 CheckBox 数据模板的 WPF ListBox - Checkbox 的绑定(bind)内容属性不起作用