我已经通过VBA代码创建了一个组合框。
Sub CreateFormControl()
ActiveSheet.DropDowns.Add(0, 0, 100, 15).Name = "ComboBox1"
ActiveSheet.Shapes("ComboBox1").ControlFormat.RemoveAllItems
Dim i As Integer
With ActiveSheet.Shapes("ComboBox1").ControlFormat
For i = 1 To 25
.AddItem i
Next i
End With
ActiveSheet.Shapes.Range(Array("ComboBox1")).Select
Selection.OnAction = "ComboBox1_Change"
Range("B2").Select
End Sub
这里的问题是,当我在ComboBox
中选择一个项目时,它会给我一个
运行时错误424.需要对象
它没有显示所选的值。我还尝试将我的声明Sub CreateFormControl()
更改为公开Sub CreateFormControl()
,但它仍然无效。
Sub ComboBox1_Change()
MsgBox (ComboBox1.Value) 'The error is here
End Sub
答案 0 :(得分:2)
尝试使用以下代码,尝试将ActiveSheet
替换为有资格的Worksheet
,例如Worksheets("YoutSheetName")
。
Sub ComboBox1_Change()
Dim ws As Worksheet
Dim MyDropDown As DropDown
' try not to use ActiveSheet, replace "Sheet1" with your sheet's name
Set ws = Worksheets("Sheet1") ' ActiveSheet
Set MyDropDown = ws.Shapes("ComboBox1").OLEFormat.Object ' <-- set my Object with "ComboBo1" drop-down
MsgBox MyDropDown.List(MyDropDown.ListIndex) '<-- display the value of the selected item
End Sub
以下是&#34;清洁工&#34;在不使用DropDown
,Worksheet
和ActiveSheet
的情况下向Select
添加新Selection
的方法(仅使用完全限定的对象)。
Sub CreateFormControl 代码
Option Explicit
Sub CreateFormControl()
Dim MyDropDown As DropDown
Dim i As Long
' set the drop-down object to the new created drop-down (replace "Sheet1" with your sheet's name)
Set MyDropDown = Worksheets("Sheet1").DropDowns.Add(0, 0, 100, 15)
' modify the drop-down properties
With MyDropDown
.Name = "ComboBox1"
.RemoveAllItems
For i = 1 To 25
.AddItem i
Next i
.OnAction = "ComboBox1_Change"
End With
End Sub