2016-02-01 37 views
1

我已經使用一個按鈕(通過單擊)來創建一個新工作表並在其上插入一個按鈕,但是我想將代碼導入到新按鈕(這裏是MyPrecodedButton)。如何將代碼導入另一頁上的Activex控件按鈕?

Private Sub CommandButton1_Click() 
Dim z As Integer 
Dim wb As Workbook 
Dim ws2 As Worksheet, wsnew As Worksheet 

Set wb = ThisWorkbook 
Set ws2 = wb.Sheets("Sheet2") 

z = ws2.Cells(2, 1).Value 

Set wsnew = Sheets.Add ' Declare your New Sheet in order to be able to work with after 
wsnew.Name = "PIAF_Summary" & z 

z = z + 1 

With wsnew.Range("A1:G1") 
     .Merge 
     .Interior.ColorIndex = 23 
     .Value = "Project Name (To be reviewed by WMO)" 
     .Font.Color = vbWhite 
     .Font.Bold = True 
     .Font.Size = 13 
End With 
ws2.Cells(2, 1).Value = z 

Dim Rngc As Range: Set Rngc = wsnew.Range("F35") 
With ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False, Left:=Rngc.Left, Top:=Rngc.Top, Width:=205, Height:=20) 
    .Name = "MyPrecodedButton" ' change the name 
End With 
End sub 

這裏是MyPrecodedButton

Public Sub MyPrecodedButton_Click() 
    MsgBox "Co-Cooo!" 
End Sub 
+0

如果你想得很好,你不必注入代碼(讓你的代碼適用於任何情況)。 – PatricK

+0

簡單的方法是通過創建模板工作表添加所需的所有控件,並根據需要將其格式化(合併,顏色等)並隱藏此工作表,並且每次需要添加新工作表時只需複製模板並給它一個新的名字,並取消隱藏它。 – Fadi

回答

1

讓我們簡單地展示你可以做什麼用VBA添加按鈕的代碼。

如果ActiveSheet不是「Sheet1」,下面的代碼將爲單元格B2添加一個按鈕。

Option Explicit 

Sub SayHello() 
    MsgBox "Hello from """ & ActiveSheet.Name & """" 
End Sub 

Sub AddButton() 
    Dim oRng As Range 
    Dim oBtns As Buttons ' Add "Microsoft Forms 2.0 Object Library" to References if you want intellisense 
    If ActiveSheet.Name <> "Sheet1" Then ' Only works if it's not "Sheet1" 
     Set oRng = Range("B2") 
     Set oBtns = ActiveSheet.Buttons 
     With oBtns.Add(oRng.Left * 1.05, oRng.Top * 1.05, oRng.Width * 0.9, oRng.Height * 2 * 0.9) 
      .Caption = "Say Hello!" 
      .OnAction = "SayHello" 
     End With 
     Set oBtns = Nothing 
     Set oRng = Nothing 
    End If 
End Sub 

之前和之後的截圖:
Before   After

現在點擊該按鈕:
Action

所以,如果你的代碼是通用的(與所有可能的情況下工作),不需要通過代碼添加代碼。即準備好您的代碼,然後只需分配按鈕的OnAction屬性即可調用正確的Sub

相關問題