将数组值分配给vba中for循环内的变量

时间:2013-06-21 08:42:44

标签: excel excel-vba vba

我有以下代码(代码1),它工作正常。它只是根据组合框的值将产品及其价格分配给单元格。我想过为每个...循环使用一个来缩短代码,以防我的客户有成千上万的产品。

CODE 2是我的实验挖掘。但是,当我将数组元素的值赋给循环内的变量时,VBA给我一个运行时错误1004类型不匹配?另外,我如何才能使用for 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 个答案:

答案 0 :(得分:1)

您的问题是For Each i In Products

这样做依次将Products的每个元素的值分配给i。然后,当你使用Products(i)时,你实际上在说,例如Products("1-2-3 ABC--150"),这是cource nonsence。

尝试改为

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