1

I have the following code (CODE 1) and it works fine. It simply assigns the product and its price to cells based on the value of the combo box. I thought of using a for each...loop to shorten the code in case my client has thousands of products.

CODE 2 is my experimental dig at this. However, when I assign the value of an array element to a variable inside the loop, VBA is giving me a run-time error 1004 type mismatch? Also, how do I could the for next...loop to accomplish my objective for a two dimensional array?

Can anyone help? I've been searching for answers all over for the past three days and I can't find any. Thanks :-)

''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
4

1 回答 1

1

你的问题是For Each i In Products

这样做是依次分配Productsto的每个元素的值。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
于 2013-06-21T08:50:14.063 回答