对于我的问题我想在不是NULL或“”的单元格旁边创建一个按钮。该按钮的标题必须遵循旁边单元格中的值。Excel VBA在单元格旁边创建一个按钮
例如:
- 我键入“员工在
Range("D3")
- 我希望宏在
Range("C3")
- 创建一个名为“雇员”按钮,不过,我想宏观上是动态的,所以每当我输入'D'列中的值时,左边的单元格将出现一个按钮。
因此,我已经想通了,我需要手动编码为CommandButton
是吗?
尽管如此,万事先感谢所有人。
对于我的问题我想在不是NULL或“”的单元格旁边创建一个按钮。该按钮的标题必须遵循旁边单元格中的值。Excel VBA在单元格旁边创建一个按钮
例如:
Range("D3")
Range("C3")
因此,我已经想通了,我需要手动编码为CommandButton
是吗?
尽管如此,万事先感谢所有人。
您可能会通过添加一个命令按钮来查看它是如何创建的,然后合并花哨的部分来记录宏。注意OLE Command按钮对象的属性,注意它们。
例如theButton.Name
却为标题通过theButton.Object.Caption
等
这里设置的代码片段,让你去: -
Option Explicit
Sub createButtons()
Dim theButton As OLEObject
Dim rngRange As Range
Dim i As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set rngRange = Sheets(2).Range("B2")
For i = 0 To 9
If rngRange.Offset(i, 0).Value <> "" Then
With rngRange.Offset(i, 1)
Set theButton = ActiveSheet.OLEObjects.Add _
(ClassType:="Forms.CommandButton.1", _
Left:=.Left, _
Top:=.Top, _
Height:=.Height, _
Width:=.Width)
theButton.Name = "cmd" & rngRange.Offset(i, 0).Value
theButton.Object.Caption = rngRange.Offset(i, 0).Value
'-- you may edit other properties such as word wrap, font etc..
End With
End If
Next i
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
输出:
@谭雄哲请给这个尝试。想象一下如何添加图片/图片,重命名它,然后将其放置在单元格中:) – bonCodigo
感谢@bonCodigo现在正在尝试 –
参考您的代码,我将每个“表格(2)”设置为“ActiveSheet” 。有一个奇怪的问题,它成功创建一个CommandButton,但同时弹出“运行时错误”438'“对象不支持此属性或方法。任何想法如何消息存在? –
尝试了这一点。
Public Sub Worksheet_Change(ByVal Target As Range)
Dim col As Integer
Dim row As Integer
col = Target.Column
row = Target.row
If Not IsNull(Target.Value) And Not IsEmpty(Target.Value) Then
Application.EnableEvents = False
Buttons.Add Cells(row, col - 1).Left, Cells(row, col - 1).Top, Cells(row, col - 1).Width, Cells(row, col - 1).Height
Application.EnableEvents = True
End If
End Sub
打开开发工具栏 - > Visual Basic,双击“Sheet1”,然后粘贴这个代码。通过在Sheet1上的单元格中输入文本然后离开该单元格(例如按Enter键)来测试它。
谢谢@Sam现在试试 –
@谭雄哲我很抱歉,我只是注意到你特别想要一个commandbutton,而不是一个普通的按钮。上述逻辑将保持不变,但您必须将“Buttons.Add”替换为[添加命令按钮]的相应代码(http://www.vbaexpress.com/forum/showthread.php?t=8907 ) – Sam
不要:)谢谢你的链接。现在检查出来。 –
首先... [你有什么尝试?](http://mattgemmell.com/2008/12/08/what-have-you-tried/)第二...看到'Worksheet_Change'事件和'宏记录器',同时做你想手动。 –
首先,我没有将按钮添加到ActiveSheet中,但对'Selection.OnAction ='没有任何线索,因为宏是我模块中的一个子集。 –
你想要按钮做什么? –