Search code examples
excelvbaradio-buttonwith-statement

How to add option button to spreadsheet?


I am trying to put together the 'Hello, World' of a macro button that will make an option/radio button on a cell in an Excel spreadsheet, the simplest possible snippet that will do the job, so I can better understand OptionButtons.Add and later build on it.

Why does the following VBA code throw an error?

"Compile error: Expected: =":

Sub BrokenOptionButtonTest()
Dim rang As Range
Set rang = Cells(Selection.Row, Selection.Column)
ActiveSheet.OptionButtons.Add(rang.Left, rang.Top, rang.Width, rang.Height)
End Sub

Why does the following VBA code not throw an error?

Sub PuzzlingOptionButtonTest()
Dim rang As Range
Set rang = Cells(Selection.Row, Selection.Column)
With ActiveSheet.OptionButtons.Add(rang.Left, rang.Top, rang.Width, rang.Height)
End With
End Sub

Solution

  • Drop the parentheses from the first one, since you're not using the return value from Buttons.Add

    In the second block you're using the return value as the subject of the With block, so no problem there.

    See VBA: Usage of parentheses for a method for example

    Sub OptionButtonTest()
        With Selection.Cells(1)
            .Parent.OptionButtons.Add .Left, .Top, .Width, .Height
        End With
    End Sub