简体   繁体   English

为VBA组合框创建动态范围

[英]Creating dynamic range for VBA Combobox

Currently I am making user form on Excel VBA and using combobox. 目前,我正在Excel VBA上并使用combobox制作用户表单。 I have range(A2:A61) named "Division" in which was included divisions of company. 我有一个名为“ Division”的范围(A2:A61),其中包括公司的部门。 When I add this data into combo row source, I put named range - Division. 当我将此数据添加到组合行源时,我将命名范围-分区。 But on the other hand divisions are dynamic, I mean new divisions are created during the year. 但另一方面,部门是动态的,我的意思是在这一年中创建了新部门。

The problem is when I created new division I can see its name on Cell A62 but it doesn't include range - named division. 问题是当我创建新的分区时,我可以在单元格A62上看到其名称,但其中不包括范围-命名的分区。 As the result I can't see updated combobox list. 结果,我看不到更新的组合框列表。

Firstly I tried to choose range as (A:A) and called it division. 首先,我尝试将范围选择为(A:A)并将其称为除法。 In this case I can see updated combobox list but the blank cells within range makes other problems for me. 在这种情况下,我可以看到更新的组合框列表,但是范围内的空白单元格对我来说还带来其他问题。

Secondly I had this code and I tried to use it as Row Source for combobox but came out error. 其次,我有此代码,我尝试将其用作组合框的行源,但出现错误。

Set Division = Worksheets("DataCMB").Range(Range("E2"), Range("E1048576").End(xlUp))

Please, help to find out the issue. 请帮忙找出问题所在。

You can insert your A2:A61 as table and define as "Division" name. 您可以将A2:A61插入表格并定义为“部门”名称。 So when you add new data, new data will auto include into "Division"name. 因此,当您添加新数据时,新数据将自动包含在“部门”名称中。

The first problem you have, and some of the other answers here have, is that you are not telling your 2nd and 3rd Range calls which sheet they should reference, so in the line below you can see I have added Worksheets("DataCMB") in front of them. 您遇到的第一个问题以及这里的其他一些问题是,您没有告诉您的第二个和第三个Range调用应该引用哪个工作表,因此在下面的行中,您可以看到我添加了Worksheets(“ DataCMB”)在他们面前。 Without that it will use the ActiveSheet which may not be set to DataCMB, so it will be looking for a range that is on a different sheet, and not find it. 否则,它将使用ActiveSheet,该ActiveSheet可能未设置为DataCMB,因此它将在其他工作表上查找范围,而找不到该范围。

The other problem was that your .End(xlUp) was working from a single cell and not a range, so I have changed it to look at the whole column and to look down instead of up. 另一个问题是您的.End(xlUp)是在单个单元格而不是范围内工作的,因此我将其更改为查看整个列,并向下而不是向上查看。 So the line below will give you the whole range of whatever is in that column, but will not include any blanks at the bottom, nor the header. 因此,下面的行将为您提供该列中所有内容的全部范围,但底部不包含任何空格,也不包含标题。

Set Division = Worksheets("DataCMB").Range(Worksheets("DataCMB").Range("E2"), Worksheets("DataCMB").Range("E2:E1048576").End(xlDown))
Private Sub UserForm_Initialize()
  Division = Range(Range("A2"), Range("A2").End(xlDown)).Address
  Me.ComboBox1.RowSource = Division
End Sub

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

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