Sunday, February 22, 2026

Add Checkboxes To Selection Excel VBA Macro

This macro adds a checkbox to each cell of the selected range, and links the check to that same cell. The position, caption, and other properties of the checkbox can be setup. Additionally, we can associate an action to each checkbox in the selection; this can be an specific action for the cell or row with the checkbox.


Macro/VBA code: 



  Sub AddCheckBoxToSelection()
  
  Dim cell As Range, check As Object
  For Each cell In Selection.Cells
      Set check = ActiveSheet.CheckBoxes.Add(cell.Left, cell.Top, cell.Height, cell.Height)
      With check
          .Caption = ""
          .LinkedCell = cell.Address
       
          'Add action (optional)
          '.Name = "check" & cell.Address(0, 0)
          '.OnAction = "CheckAction"

      End With
  Next cell
  
  End Sub


Macro explained:

  • First we declare a Range object variable (cell) that will hold each cell in the selection, and an object variable (check) to hold the checkbox shape for each cell.
  • Then we start a For Each loop through all cells in the selection.
  • For each cell, we add a checkbox shape within the cell. The checkbox is aligned to the left of the cell. Alternatively, we can align the checkbox to the right or center of the cell as indicated below.

  x = cell.Left + cell.Width - cell.Height  'aligned to the right
  x = cell.Left + (cell.Width / 2) - (cell.Height / 2)  'aligned to center


  • We can then set certain properties of the checkbox such as the caption (intentionally left blank) and the linked cell (being the cell itself).
  • Optionally, we may want to associate an action to the checkbox, that will execute by calling another macro. That can be a general action or an action specific of each checkbox, and therefore, to its cell. With that purpose, we probably want to set a specific name for the checkbox shape that contains the cell address.
  • When needed, we can remove all the checkboxes in the active sheet by using a For Each loop and deleting each checkbox as shown below.

  For Each check In ActiveSheet.CheckBoxes
      check.Delete
  Next


This is how we add checkboxes to the selection in Excel with VBA macros.


Other examples:


No comments:

Post a Comment

Popular Posts