创建具有不同查找范围的按钮

时间:2015-11-10 12:28:00

标签: excel vba excel-vba

使用它来创建按钮: -

Sub CreateButton4()
Dim i&
With ActiveSheet
    i = .Shapes.Count
    With .Buttons.Add(199.5, 20 + 46 * i, 81, 36)
        .Name = "New Button" & Format(i, "00")
        .OnAction = "MoveValue"
        .Characters.Text = "Submit " & Format(i, "00")
    End With
End With

运行MoveValue()子: -

Sub MoveValue()
With Sheets("Sheet1").Columns(8).Find(Range("C3").Value, , , 1).Offset(0, 1)
    .Value = .Value + Sheets("Sheet1").Range("D3").Value
End With

问题是我希望MoveValue()与它相邻的单元格相关联,因为我有另一个sub,它在创建按钮时将数据提交给相邻的单元格(此时我只是将它写入工作第一个按钮)。不确定我是否完全以错误的方式解决这个问题。任何帮助将不胜感激。

Image Spreadsheet1 Image Spreadsheet1

1 个答案:

答案 0 :(得分:0)

您可以使用属性TopLeftCell,如图所示here。但是你必须像这样改变你的布局,所以按钮的左上角单元格与你想要的信息位于同一行。

enter image description here

    Sub CreateButton4()
      Dim i&
      With ActiveSheet
        i = .Shapes.Count
          With .Buttons.Add(199.5, 35 + 46 * i, 81, 36)
            .Name = "New Button" & Format(i, "00")
            .OnAction = "MoveValue"
            .Characters.Text = "Submit " & Format(i, "00")
         End With
      End With
  End Sub



  Sub MoveValue()

        Dim tlcRow As Integer

        tlcRow = ActiveSheet.Shapes(Application.Caller).TopLeftCell.row

        With Plan1
            .Range("H3:H8").Find(.Range("C" & tlcRow).Value).Offset(0, 1).Value = .Range("D" & tlcRow).Value
        End With

    End Sub