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
感谢您的洞察力克里斯。我使用提供的提示重新编写了我的代码,并且工作完美无瑕。现在我需要在二维数组上做这件事来考虑产品的价格。以下是现在可用的代码:For i = LBound(Products)To UBound(Products) If Sheet1.Product1ComboBox.Value = Products(i)Then Sheet1.Range(“H2”)。Value = Products(i) 退出 结束如果 下一个我 – Kazuo
很高兴有帮助。现在你应该花点时间了解SO的工作原理。接受你认为可以解答你的问题的答案。首先研究(关于二维数组,有许多关于SO的答案),如果还有问题,请提出另一个问题 –