如何相对于单元格(值)插入命令按钮?

时间:2019-04-15 14:16:32

标签: excel vba

我想要一个VBA代码来放置此按钮,以便说两个单元格(在右侧)与工作表中的“ hello”单元格相距较远。这是命令按钮代码:

Set objBtn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False _
    , DisplayAsIcon:=False, Left:=480, Top:=200, Width:=90, Height:= _
     30)
objBtn.Name = "button1"

我不想使用单元格位置作为参考,而是使用单元格值为“ hello”。因此,也许首先我要查找值,然后相对于其插入命令按钮。

2 个答案:

答案 0 :(得分:1)

是的,就是这样做的方式,例如

Sub x()

Dim objBtn As OLEObject, r As Range

Set r = Cells.Find("hello") 'should specify more parameters than this
If Not r Is Nothing Then
    Set objBtn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, _
                 DisplayAsIcon:=False, Left:=r.Offset(, 2).Left, Top:=r.Top, Width:=90, Height:=30)
    objBtn.Name = "button1"
End If

End Sub

答案 1 :(得分:0)

'您可以将按钮固定到此处的特定单元格A1

Dim rngcbn1 As Range
 Set rngcbn1 = ActiveSheet.Range("A1")
 With ActiveSheet.OLEObjects("CommandButton1")
        .Top = rngcbn1.Top
        .Left = rngcbn1.Left
        .Width = rngcbn1.Width
        .Height = rngcbn1.RowHeight
 End With