2016-05-20 38 views
-1

我有一些數組和excel vba中的組合框,當從活動程序設置hozelistname值combobox1。陣列如下:使用字符串值vba中的數組名稱的框架

hozelistname=("zahedan","zabol") 
hozezahedan=(1,2,3,4) 
hozezaol=(5,6,7) 

現在當combobox1改變,我希望它顯示所選數組的列表。例如,當我從列表中選擇zahedan時,我希望它警告名爲hozezahedan的zahedan數組的值以及zabol。 我寫了下面的代碼,但不工作!任何機構來幫助我?

Private Sub ComboBox1_Change()  
    dim arrayname,str as string 
    dim i as integer 
    arrayname = "hoze" & ComboBox1.text 

    for i= lbound(arrayname) to ubound(arrayname) 
    msgbox(arryname(i)) 
    next 
End Sub 
+0

將您的數組添加到字典中並使用該密鑰命名它們。像dictionary.add「Hoze_Test」,arrTest())然後你可以引用使用「Hoze_Test」集的arrUse = dictionary(「Hoze_Test」)這個沒有測試過的代碼,只是建議,看一下字典。 –

+0

你能寫出正確的代碼嗎? –

回答

1
Option Explicit 

Private dicArrays As Scripting.Dictionary 

Sub SetUP() 

Dim arrTestOne(5) As String 
Dim arrTestTwo(10) As String 

Set dicArrays = New Scripting.Dictionary 

dicArrays.Add "TestOne", arrTestOne 
dicArrays.Add "TestTwo", arrTestTwo 

End Sub 

Sub Reference_Example() 

Dim a() As String 

a = dicArrays("TestTwo") 

End Sub 

我希望這說明了一點。

+0

你認爲我的陣列像hozename(hoze1 ... hoze50)一樣大。併爲每個項目我有另一個數組,例如我需要寫'dicArrays.Add「hoze1」,arrhoze1,..... dicArrays.Add「hoze50」,arrhoze50'? –

+0

它有一個錯誤「'user-definde type not definde'」 –

+0

您將不得不包含Scripting.Dictionary類的引用。在VBEditor中,轉至工具 - >參考並選擇/檢查「Microsoft Scripting Runtime」,然後單擊確定按鈕 –

0

它不清楚你在做什麼,但下面有幫助你通過它嗎?

'This block of code goes right at the top of the form 
Option Explicit 
Dim hozelistname(1) As String 
Dim hozezahedan(3) As String 
Dim hozezabol(2) As String 

Private Sub ComboBox1_Change() 
Dim i   As Integer 
Dim AryLocal() As String 

'set the local array based on the combobox 
Select Case Me.ComboBox1 

    Case "zahedan" 
     AryLocal = hozezahedan 

    Case "zabol" 
     AryLocal = hozezabol 

    Case Else 
     ReDim AryLocal(0) 

End Select 

'show the local array 
For i = 0 To UBound(AryLocal, 1) 
    MsgBox (AryLocal(i)) 
Next 

End Sub 

Private Sub UserForm_Activate() 
Dim LngCounter As Long 

'Set up the lists 
hozelistname(0) = "zahedan" 
hozelistname(1) = "zabol" 

'Set up each result 
hozezahedan(0) = "1" 
hozezahedan(1) = "2" 
hozezahedan(2) = "3" 
hozezahedan(3) = "4" 
hozezabol(0) = "5" 
hozezabol(1) = "6" 
hozezabol(2) = "7" 

'set the combobox 
For LngCounter = 0 To UBound(hozelistname, 1) 
    Me.ComboBox1.AddItem hozelistname(LngCounter) 
Next 

End Sub 

接下來的步驟是根據在Excel中編寫的列表填充組合框和數組,而不是硬編碼列表。

相關問題