Customize ActiveX button from VBA

社会主义新天地 提交于 2020-03-03 12:58:12

问题


I've made a piece of code that, when you click a button, copies a sheet, strips it for formatting and then adds a new button with a different macro assigned to it.

My problem is that both of my buttons are grey, and I would like to customize them.

The first button is an Excel control element, and is always present on the original sheet. I've altered the font, font size, underlining and made it bold, by right clicking on it and entering the formatting menu, but I can't find the option to change its background color.

The second button is created through VBA and is an ActiveX button. The code to add it is as follows

Sub TilføjKnap()
Dim Plads As Range
Dim Knap As OLEObject
Dim Kode As String

    Sheets("Indleveringsplan (2)").Activate
        Set Plads = ActiveSheet.Range("L7:N17")

        Set Knap = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False)

        With Knap
            .Name = "EksportKnap"
            .Object.Caption = "Eksporter til PDF"
            .Left = Plads.Left + 10
            .Top = Plads.Top
            .Width = Plads.Width - 10
            .Height = Plads.Height
            .PrintObject = False
        End With

        Kode = "Private Sub EksportKnap_Click()" & vbNewLine
        Kode = Kode & "Call Eksporter" & vbNewLine
        Kode = Kode & "End Sub"

        With ActiveWorkbook.VBProject.VBComponents(Worksheets("Indleveringsplan (2)").CodeName).CodeModule
            .InsertLines .CountOfLines + 1, Kode
        End With

    End Sub

I'm assuming that I need to add something along the lines of BackgroundColor inside the With Knap, but I can't get it to work.

That being said, I would also like to underline the text, change its font and font size as well as make it bold.


回答1:


The OleObject encapsulates the CommandButton and exposes its interface via .Object so .Object.BackColor = vbRed.

You can use a typed variable to get intellisense:

Dim Button As CommandButton
With Knap
    Set Button = .Object
    With Button
        .Caption = "Eksporter til PDF"
        .BackColor = vbRed
        .Font.Underline = True
        ...
    End With
    ...
End With


来源:https://stackoverflow.com/questions/43542282/customize-activex-button-from-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!