2012-12-21 139 views
1

對於我的問題我想在不是NULL或「」的單元格旁邊創建一個按鈕。該按鈕的標題必須遵循旁邊單元格中的值。Excel VBA在單元格旁邊創建一個按鈕

例如:

  1. 我鍵入「員工在Range("D3")
  2. 我希望宏在Range("C3")
  3. 創建一個名爲「僱員」按鈕,不過,我想宏觀上是動態的,所以每當我輸入'D'列中的值時,左邊的單元格將出現一個按鈕。

因此,我已經想通了,我需要手動編碼爲CommandButton是嗎?

儘管如此,萬事先感謝所有人。

+0

首先... [你有什麼嘗試?](http://mattgemmell.com/2008/12/08/what-have-you-tried/)第二...看到'Worksheet_Change'事件和'宏記錄器',同時做你想手動。 –

+0

首先,我沒有將按鈕添加到ActiveSheet中,但對'Selection.OnAction ='沒有任何線索,因爲宏是我模塊中的一個子集。 –

+0

你想要按鈕做什麼? –

回答

3

您可能會通過添加一個命令按鈕來查看它是如何創建的,然後合併花哨的部分來記錄宏。注意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 

輸出:

enter image description here

+0

@譚雄哲請給這個嘗試。想象一下如何添加圖片/圖片,重命名它,然後將其放置在單元格中:) – bonCodigo

+0

感謝@bonCodigo現在正在嘗試 –

+0

參考您的代碼,我將每個「表格(2)」設置爲「ActiveSheet」 。有一個奇怪的問題,它成功創建一個CommandButton,但同時彈出「運行時錯誤」438'「對象不支持此屬性或方法。任何想法如何消息存在? –

2

嘗試了這一點。

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鍵)來測試它。

+0

謝謝@Sam現在試試 –

+0

@譚雄哲我很抱歉,我只是注意到你特別想要一個commandbutton,而不是一個普通的按鈕。上述邏輯將保持不變,但您必須將「Buttons.Add」替換爲[添加命令按鈕]的相應代碼(http://www.vbaexpress.com/forum/showthread.php?t=8907 ) – Sam

+0

不要:)謝謝你的鏈接。現在檢查出來。 –

相關問題