Assigning an array value to a variable inside a fo

2019-08-04 10:59发布

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

1条回答
Deceive 欺骗
2楼-- · 2019-08-04 11:40

Your problem is the For Each i In Products

What this does is assign the value of each element of Products to i in turn. Then when you use Products(i) you are in effect saying, eg Products("1-2-3 ABC--150") which is of cource nonsence.

Try instead

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

or

For Each Product In Products
    If Product = Sheet1.Product1ComboBox.Value Then
        Sheet1.Range("H2").Value = Product
        Exit For
    End If
Next
查看更多
登录 后发表回答