使用 Headers 创建多列列表框 - 运行 时间错误“70”权限被拒绝

Creating Multi Column ListBox with Headers - Run Time Error '70' Permission Denied

我正在尝试将一系列数据添加到多列列表框,当我从我构建的数组创建列表框时,出现错误:Run Time Error '70' Permission Denied

我有完整的 read/write 访问权限,我收到此错误应该不是什么原因。这是我的代码:

    Option Explicit
    
    Private Sub UserForm_Initialize()
    Dim wb As Workbook, ws As Worksheet
    Dim i As Integer, j As Integer, a As Integer
    Dim LastRow As Integer, LastCol As Integer
    Dim v As Variant
    Dim hits As Collection
    Dim hit As Variant
    Dim arrItems() As Variant
    
    Application.ScreenUpdating = False
    Me.ListBox1.Clear
    
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("New")
    
    LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
    LastCol = ws.Cells(1, Columns.Count).End(xlToLeft).Column
    
    WireEnt.ListBox1.ColumnCount = 10
    WireEnt.ListBox1.ColumnWidths = "50,50,50,50,50,50,50,50,50,50"
        With Me.ListBox1
         .ColumnHeads = True
         .RowSource = "C2:L" & LastRow
        End With
    
    For i = 1 To 1
     For j = 1 To LastCol
        If ws.Cells(i, j) = "Date Wire Entered" Then
         a = j
         Exit For
        End If
     Next j
    Next i
    
    'Read values into an array
    v = ws.Range(ws.Cells(2, 3), ws.Cells(LastRow, a))
    
    'Find the target values
    Set hits = New Collection
     For i = 1 To UBound(v, 1)
        If v(i, a - 2) = "" Then hits.Add i
    Next
    
    
    'Populate the listbox array with the hit items
    If hits.Count > 0 Then
        ReDim arrItems(1 To hits.Count, 1 To UBound(v, 2))
        i = 1
            For Each hit In hits
                For j = 1 To 10
                 arrItems(i, j) = v(hit, j)
                Next
            i = i + 1
            Next
        Me.ListBox1.List = arrItems
    Else
        'There are not hits so clear the listbox
        Me.ListBox1.Clear
    End If
    
    Application.ScreenUpdating = True
    End Sub

导致错误的代码行是:

Me.ListBox1.List = arrItems

请帮忙!

有几个问题:

  • 主要问题是 .RowSource 属性 绑定到预定义范围 不与动态数组分配合作。因此执行 Me.ListBox1.List = arrItems 与不同的数据范围冲突,将引发 Run Time Error '70' Permission Denied.

    不使用 .RowSource 的缺点是您牺牲了自动获得 ColumnHeads 的可能性。

  • 不要在后面的表单代码模块中引用UserForm的名称,就可以了 为 Me 关键字添加前缀(例如 Me.ListBox1.ColumnCount)或 单独引用控件(例如 ListBox1.ColumnCount

  • 要分隔列条目,请使用分号 (;) 作为列表分隔符。所以使用

     Me.ListBox1.ColumnWidths = "50;50;50;50;50;50;50;50;50;50"
    

可能的解决方案

  • 因此,一个简单的解决方法是将 header 作为第一个数据行。
  • 另一种经常使用的方法是在需要一些编码来定义宽度的列表框顶部填充标签。
  • 另一种方法是使用另一个列表框 header 标题仅在列表框上方。
  • 或者,您可以将需要的数据写入另一个(隐藏)范围,并且每次 refresh/redefine .RowSource