[英]Move Combobox onclick of a button to a next row excel VBA
我已经创建了一个vba代码来创建组合框,并填充了我的命名范围。 现在,当我从组合框中选择某项内容时,我想使其在当前单元格中设置该值,并且它应该移至下一行,以便我可以继续在组合框中为每个单元格设置一个值。
我有以下代码来创建组合框,但我不知道如何使用.onaction使它移动到下一行
Sub AddComboBoxes()
Dim cb As Object
Dim aCell As Range, r As Long
For i = 1 To 1
Set aCell = Sheet1.Cells(i, 5)
Set cb = Sheet1.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Left:=aCell.Left, Top:=aCell.Top, Width:=aCell.Width, Height:=aCell.Height)
cb.Placement = xlMoveAndSize
cb.Name = "ComboBoxN1"
cb.ListFillRange = "N1"
cb.OnAction = "N1.value"
Next
End Sub
请帮忙。
就像我提到的.OnAction
不是OLEObjects
的属性而是DropDowns
的属性
参见此示例,该示例将在Col 5中创建下拉菜单5次,并将"Sheet2!A1:A5"
分配为ListFillRange
并在DropDown中选择一个选项时执行CallMe
。
逻辑:
"ComboBoxN" & i
,以便我们稍后可以检索它们所在的行。 Sub CallMe()
中确定行号的逻辑 码:
Sub AddComboBoxes()
Dim cb As Object
Dim aCell As Range
Dim i As Long
For i = 1 To 5
Set aCell = Sheet1.Cells(i, 5)
Set cb = Sheet1.DropDowns.Add(aCell.Left, aCell.Top, aCell.Width, aCell.Height)
cb.Placement = xlMoveAndSize
cb.Name = "ComboBoxN" & i
cb.ListFillRange = "Sheet2!A1:A5"
cb.OnAction = "CallMe"
Next
End Sub
您的CallMe
应该是这样的
Sub CallMe()
Dim rw As Long
Dim cb As Object
'~~> Extract the number from the dropdown to
'~~> identify which row is it in
rw = Val(Trim(Replace(Application.Caller, "ComboBoxN", "")))
Set cb = Sheet1.DropDowns(rw)
'~~> We are setting the value in Col A. Chnage as applicable
Sheet1.Range("A" & rw).Value = cb.Value
'~~> Activate the next cell.
Sheet1.Range("A" & rw + 1).Activate
End Sub
屏幕截图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.