【问题标题】:How to create a Listbox with dynamic Rowsource in VBA如何在 VBA 中创建具有动态行源的列表框
【发布时间】:2021-06-26 06:33:13
【问题描述】:

我收到一个名为(运行时错误“13”;类型不匹配)的错误。 我是 VBA 新手,如果这是一个愚蠢的问题,我很抱歉。

BaseForm = 我的用户表单

将 iRow 和 iCol 调暗为整数

sub refresh_data() '刷新列表框数据

Set ws = ThisWorkbook.Sheets("DATA")

iRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
iCol = ws.Cells(1, Columns.Count).End(xlToLeft).Column
 
With BaseForm

    .ListBox1.ColumnCount = iCol
    .ListBox1.ColumnHeads = True
    
    If iRow > 1 Then
    .ListBox1.RowSource = Range(Cells(1, 1), Cells(iRow, iCol))
    
    Else
    .ListBox1.RowSource = Range(Cells(1, 1), Cells(1, iCol))

    End If
End With

结束子

【问题讨论】:

标签: vba dynamic listbox


【解决方案1】:
  1. 处理 Excel 行时,使用Long 而不是Integer
  2. 完全限定您的范围对象。你们很多人都想阅读Why does Range work, but not Cells?
  3. .RowSource 需要 String

这是你正在尝试的吗? (未测试

Option Explicit

Dim iRow As Long
Dim iCol As Long

Sub refresh_data() ' refresh the listbox data
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("DATA")

    iRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
    iCol = ws.Cells(1, Columns.Count).End(xlToLeft).Column
 
    With BaseForm
        .ListBox1.ColumnCount = iCol
        .ListBox1.ColumnHeads = True
    
        If iRow > 1 Then
            .ListBox1.RowSource = "'" & ws.Name & "'!" & _
                                  ws.Range(ws.Cells(1, 1), ws.Cells(iRow, iCol)).Address
        Else
            .ListBox1.RowSource = "'" & ws.Name & "'!" & _
                                  ws.Range(ws.Cells(1, 1), ws.Cells(1, iCol)).Address
        End If
    End With
End Sub

【讨论】:

  • 感谢您的解释和快速回复!很有帮助
猜你喜欢
  • 1970-01-01
  • 2021-03-14
  • 2018-12-02
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多