简体   繁体   中英

Excel Visual Basic Code Issue

I'm designing a PO that changes the cost per unit depending on the item selected in the Drop Down List.

I'm using...

Sub DropDown8_Change()
If (DropDown8.SelectedItem = "1") Then
    Range("E21").Value = "54.90"
End If
End Sub

However I get the error,

Run-time error '424': Object required

If I remove the IF statement and have it simply change the contents of the Cell, It works.. So I'm assuming it is an issue with the Conditional Statement.

From my signifigant past with Visual Basic in Visual Studio, The name of the Control is included in the Method so I'm confused. I could be doing alot wrong here so bear with me :).

Thanks in advance

Working with Shapes on an Excel worksheet is kind of annoying. I usually stay away from them if I can.

Here's how you get the data you're looking for:

Sub DropDown8_Change()
    Dim selectedItem As String
    Dim ws As Excel.Worksheet
    Set ws = Sheets(1)

    Dim selectedIndex As Long
    selectedIndex = ws.Shapes("Drop Down 8").ControlFormat.Value
    selectedItem = ws.Shapes("Drop Down 8").ControlFormat.List(selectedIndex)

    If (selectedItem = "1") Then
        Range("E21").Value = "54.90"
    End If
End Sub

The problem is that the method that's generated for you (in your case, DropDown8_Change() ) doesn't really give you much to work with (like with Worksheet_Change(ByVal Target As Range) ), and you have to deal with VBA Shapes (yuck).

You need to reference the Shape by it's actual name (unless you know the Shape's index, which isn't as easy to determine). The name can be found by right-clicking on the shape and then looking in the Range address textbox to the left of the formula bar. Then you have to go through this whole ControlFormat hoops to get what you're looking for.

Sorry for the rant. I hate VBA Shapes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM