Excel VBA在单元格旁边创build一个button
对于我的问题,我想在不是NULL或“”的单元旁边创build一个button。 该button的标题必须跟在旁边单元格中的值。
例如:
- 我在
Range("D3")
键入“EMPLOYEE” - 我希望macros在
Range("C3")
创build一个名为“EMPLOYEE”的button - 但是我希望这个macros是dynamic的,这样每次我input“D”列中的值时,左边的单元格 –
C3
将会出现一个button。
因此,我已经想通了,我需要手动编写CommandButton
是吗?
尽pipe如此,万事先谢谢了。
您可以通过添加一个命令button来logging一个macros ,看看它是如何创build的,然后将这些花哨的部分合并起来。 注意OLE Commandbutton对象的属性,注意它们。
例如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
输出:
试试这个。
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上的单元格中input文本,然后远离该单元格(例如按Enter键)来testing它。