2017-03-03 84 views
0

我在Excel中遇到VBA问题。我的目标是拥有一个带有几个组合框的用户窗体,所有内容都是从Excel图表中提取的。 我用命令Excel VBA与字符串数组编译错误

ComboBox.Rowsource = "A1:A10"

而且,对于每一个组合框,我在我的窗体。然后我意识到这是很多代码,因为我再次为每个盒子写了这个命令。所以我试着用一个字符串数组,把它称为“A”,内容为“Combobox1”和“Combobox2”等等。 但是当我试图在代码中使用此 -

for i = 1 to 10

A(i-1).rowsource = "A1:A10"

next

  • 我得到了警告:编译错误:Invalide预选赛

什么是我的错?

很多感谢任何帮助,D.K.

+0

要找出为什么你得到'编译错误',我们需要看完整的代码。 – dee

回答

0

您可以使用ComboBoxList属性从范围(栏)填写您的组合框的使用值:

ComboBox.List = Range("A1:A10").Value 

A阵列填充值ComboBox,您可以使用代码下面:

Dim A() As Variant 

A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) '<-- populate array (for example) 
ComboBox.List = A '<-- populate combo-box with array values 

要填充A阵列值从Range,后来就填充您ComboBoxA阵列,使用下面的代码:

Dim A() As Variant 

A = Application.Transpose(Range("A1:A10")) '<-- populate array from Range("A1:A10") 
ComboBox.List = A '<-- populate combo-box with array values 
0

而不是string array你可以使用VBA.Collection存储形式的组合框。这可能更容易,然后array

Dim i As Integer 
Dim A As Collection 
Set A = New VBA.Collection 

' One way of adding specific comboboxes to the collection 
A.Add Me.ComboBox1, Me.ComboBox1.Name 
A.Add Me.ComboBox2, Me.ComboBox2.Name 
A.Add Me.ComboBox3, Me.ComboBox3.Name 
' and so on for all combo boxes on the form 

Set A = New VBA.Collection 

' Another way would be to loop through the controls and filter the comboboxes out 
Dim c As MSForms.control 
For Each c In Me.Controls 
    If TypeName(c) = "ComboBox" Then 
     A.Add c, c.Name 
    End If 
Next c 

For i = 1 To A.Count 
    A(i).RowSource = "A1:A10" 
Next