插入按钮的代码有效,但在向按钮添加背景颜色时会出现438错误

时间:2015-07-16 11:45:49

标签: excel-vba button vba excel

插入按钮的代码工作正常,但当我尝试向按钮添加背景颜色时,我得到error 438

ActiveSheet.CommandButton1.BackColor = RGB(255, 0, 0)

我尝试过这种变化,但我没有得到它

由于

Sub CreateButton()
Dim Obj As Object
Dim Code As String


Sheets(1).Select

'create button
Set Obj = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
Link:=False, DisplayAsIcon:=False, Left:=200, Top:=100, Width:=100, Height:=35)
Obj.Name = "CommandButton1"
'buttonn text
ActiveSheet.OLEObjects(1).Object.Caption = "Test Button"
'button color
ActiveSheet.CommandButton1.BackColor = RGB(255, 0, 0)

'macro text
Code = "Sub CommandButton1_Click()" & vbCrLf
Code = Code & "Call Tester" & vbCrLf
Code = Code & "End Sub"
'add macro at the end of the sheet module
With ActiveWorkbook.VBProject.VBComponents(Worksheets(1).CodeName).CodeModule
    .insertlines .CountOfLines + 1, Code
End With
End Sub

Sub Tester()
MsgBox "You have click on the test button"
End Sub

1 个答案:

答案 0 :(得分:1)

您必须引用Object的{​​{1}}对象。我知道这听起来有点多余,所以请看下面的简化代码,如果您需要帮助,请告诉我。

OleObject