我正在尝试在excel的单元格中插入一个相对按钮。实际上,我想要的是,一个单元格内的按钮,当添加/删除行/列时可以相对移动。此外,我希望它在包含按钮的单元格下方的单元格中加载特定文本。可以在excel中完成吗?我不知道该怎么办! VB新手!!任何帮助表示赞赏:)
编辑::
要定位相对按钮,我使用以下代码:
Sub buttonInACell()
Dim btn As Button
Dim t
Set t = ActiveSheet.Cells(10, 6)
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
End Sub
现在我需要在按钮上添加一个宏来在它下面的单元格中加载一个值。我想我应该使用TopLeftCell
属性。但是我怎么能参考按钮呢?
答案 0 :(得分:1)
要为按钮指定宏,可以使用其OnAction属性 - 将其设置为要调用的宏的名称。在该宏内部,您可以使用Application.Caller获取按钮的名称,并使用该名称来确定要采取的操作。
Sub buttonInACell()
Dim btn As Button
Dim t, x
For x = 1 To 5
Set t = ActiveSheet.Cells(2, x)
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
btn.OnAction = "ClickedMe"
Next x
End Sub
Sub ClickedMe()
Dim c, s
c = Application.Caller
Set s = ActiveSheet.Shapes(c)
s.TopLeftCell.Offset(1, 0).Value = "clicked"
End Sub
答案 1 :(得分:0)
谢谢@Tim的回答!实际上我厌倦了弄清楚自己,我按照我的要求达成了解决方案,如下:
将按钮放在单元格中::
Sub buttonInACell()
Dim btn As Button
Dim t
Set t = ActiveSheet.Cells(10, 6)
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
End Sub
点击按钮::
Public flag As Integer
Sub buttonInACell_Click()
Dim row As Integer, col As Integer
'flag=0 : no show, flag=1 : show
row = ActiveSheet.Shapes(Application.Caller).TopLeftCell.row
col = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Column
If flag = 0 Then
ActiveSheet.Shapes(1).TextFrame.Characters.text = "Show data"
If ActiveSheet.Cells(row + 2, col).Font.Color = vbRed Then
ActiveSheet.Cells(row + 2, col).Value = ""
End If
ActiveSheet.Cells(row + 2, col).Font.Color = vbWhite
ActiveSheet.Cells(row + 2, col).WrapText = False
flag = 1
ElseIf flag = 1 Then
ActiveSheet.Shapes(1).TextFrame.Characters.text = "Hide Data"
If ActiveSheet.Cells(row + 2, col).Value = "" Then
ActiveSheet.Cells(row + 2, col).WrapText = True
ActiveSheet.Cells(row + 2, col).Font.Color = vbRed
ActiveSheet.Cells(row + 2, col).Value = "Sorry! No Sample Data As of Yet!"
Else
ActiveSheet.Cells(row + 2, col).WrapText = True
ActiveSheet.Cells(row + 2, col).Font.Color = vbBlack
End If
flag = 0
End If
End Sub
这实际上是做什么的,它创建了一个切换按钮,允许切换相对单元格中的数据! :)