简体   繁体   English

VBA Excel将具有动态大小的范围添加到组合框列表

[英]VBA Excel Adding Range With Dynamic Size To Combobox List

I have a range within the workbook that I'd like to set to the list of items in a Combobox from one of my Userforms. 我要在工作簿中设置一个范围,该范围要设置为我的一个用户窗体中“组合框”中的项目列表。 The issue is the Range can be any size. 问题是范围可以是任何大小。 I currently handle the zero case by exiting the Sub , but when there's only one element in the range. 我目前通过退出Sub处理零值情况,但是当范围中只有一个元素时。

When there's one element, instead of returning an array of elements, it only returns a single String element and the listbox gives me an error: `Run-time error '381': Could not set the List property. 如果有一个元素,则不返回元素数组,而仅返回一个String元素,并且列表框给我一个错误:运行时错误381:无法设置List属性。 Invalid property array index'. 无效的属性数组索引”。 Is there anyway to handle this besides creating an exception for the case where there's only one element? 除了为只有一个元素的情况创建例外之外,是否还有其他方法可以解决此问题?

Here's the code: Edit: Fixed program to accurately represent problem. 下面是代码:编辑:修复了程序以准确表示问题。

Private Sub UserForm_Activate()
    Dim formList As Variant
    Dim lastRow As Long
    lastRow = getLastRowInCol(Sheets("HiddenVariables"), "B")
    If lastRow = 0 Or lastRow = 1 Then Exit Sub 
    formList = Sheets("HiddenVariables").Range("B2:B" & lastRow).value 'If lastRow =2 then run-time error 381 is thrown
    Me.ComboBox.list = formList
End Sub

解决方案同样的问题

One approach is to use named range and RowSource property of combobox. 一种方法是使用组合框的命名范围和RowSource属性。

Define a named range : 定义一个命名范围:

在此处输入图片说明

Then simply set the rowsource 然后只需设置行源

Option Explicit

Private Sub UserForm_Activate()
    Me.ComboBox1.RowSource = "Sheet1!Combo_Source"
End Sub

Going by your approach, use this: 按照您的方法,使用以下方法:

If IsArray(formList) Then
        Me.ComboBox1.List = formList
     Else
        Me.ComboBox1.List = Split(formList, "") '/Converts str to arr on the fly.
   End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM