2013-06-21 167 views
0

我有以下代碼(代碼1),它工作正常。它只是根據組合框的值將產品及其價格分配給單元格。我想爲每個...循環使用a來縮短代碼,以防我的客戶端擁有數千種產品。將數組值賦給for循環中的變量vba

CODE 2是我對此的實驗性挖掘。但是,當我將一個數組元素的值賦給循環內的一個變量時,VBA會給我一個運行時錯誤1004類型不匹配?另外,我如何能爲next ...循環來完成我的二維數組的目標?

任何人都可以幫忙嗎?過去三天我一直在尋找答案,我找不到任何答案。感謝:-)

''CODE 1 
Private Sub Product1ComboBox_Change() 

'Fills in Product and Price columns. 
If Sheet1.Product1ComboBox.Value = "1-2-3 ABC" Then 
    Sheet1.Range("H2").Value = "1-2-3 ABC" 
    Sheet1.Range("I2").Value = "150.00" 
ElseIf Sheet1.Product1ComboBox.Value = "1-3 Pick Up Sticks" Then 
    Sheet1.Range("H2").Value = "1-3 Pick Up Sticks" 
    Sheet1.Range("I2").Value = "89.00" 
ElseIf Sheet1.Product1ComboBox.Value = "Meat and Potatoes" Then 
    Sheet1.Range("H2").Value = "Meat and Potatoes" 
    Sheet1.Range("I2").Value = "140.00" 
ElseIf Sheet1.Product1ComboBox.Value = "Pigs in a Blanket" Then 
    Sheet1.Range("H2").Value = "Pigs in a Blanket" 
    Sheet1.Range("I2").Value = "140.00" 
Else 
    Sheet1.Range("H2").Value = "Simply Toasted" 
    Sheet1.Range("I2").Value = "65.00" 
End If 

'Computes amount. 
Sheet1.Range("J2").Value = Sheet1.Range("I2").Value * Sheet1.Qty1ComboBox.Value 

End Sub 

''CODE 2 
Private Sub Product1ComboBox_Change() 

Dim Products(1 To 5) 
Dim i 
Dim Product 

Products(1) = "1-2-3 ABC--150" 
Products(2) = "1-3 Pick Up Sticks--89" 
Products(3) = "Meat and Potatoes--140" 
Products(4) = "Pigs in a Blanket--140" 
Products(5) = "Simply Toasted--65" 

For Each i In Products 
    Product = Products(i) 'PROBLEM: RUN-TIME ERROR 13 TYPE MISMATCH. 
    If Products(i) = Sheet1.Product1ComboBox.Value Then 
     Sheet1.Range("H2").Value = Products(i) 'PROBLEM: RUN-TIME ERROR 13 TYPE MISMATCH. 
    Exit For 
    End If 
Next i 

'Computes amount. 
Sheet1.Range("J2").Value = Sheet1.Range("I2").Value * Sheet1.Qty1ComboBox.Value 

End Sub 

回答

1

你的問題是For Each i In Products

這樣做是什麼的Products每個元素的值依次分配給i。那麼當你使用Products(i)時,你實際上是在說,例如Products("1-2-3 ABC--150")這是一個不存在的資源。

嘗試,而不是

For i = LBound(Products) to UBound(Products) 

For Each Product In Products 
    If Product = Sheet1.Product1ComboBox.Value Then 
     Sheet1.Range("H2").Value = Product 
     Exit For 
    End If 
Next 
+0

感謝您的洞察力克里斯。我使用提供的提示重新編寫了我的代碼,並且工作完美無瑕。現在我需要在二維數組上做這件事來考慮產品的價格。以下是現在可用的代碼:For i = LBound(Products)To UBound(Products) If Sheet1.Product1ComboBox.Value = Products(i)Then Sheet1.Range(「H2」)。Value = Products(i) 退出 結束如果 下一個我 – Kazuo

+0

很高興有幫助。現在你應該花點時間瞭解SO的工作原理。接受你認爲可以解答你的問題的答案。首先研究(關於二維數組,有許多關於SO的答案),如果還有問題,請提出另一個問題 –