I am trying to insert user form checkboxes in column C of my excel file because i’ll use logic in another macro to see if they are checked and write information to word based on that. This code worked the first maybe 50 times I ran it and suddenly today it doesn’t work even though I didn’t change anything.
This is what I get:
Image of checkbox positioning
This is the code I am using:
Sub InsertCheckBoxes()
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Dim cb As CheckBox
Dim cbHeight As Double
Dim cbWidth As Double
' Set the worksheet where you want to insert checkboxes
Set ws = ThisWorkbook.Sheets("Sheet1")
' Define the range where checkboxes will be inserted
Set rng = ws.Range("C34:C59")
' Loop through each cell in the range and insert checkboxes
For Each cell In rng
' Add a checkbox for each cell
Set cb = ws.CheckBoxes.Add(cell.Left, cell.Top, cell.Width, cell.Height)
' Pre-check the checkbox and set the linked cell to TRUE
cb.Value = xlOn
' Link the checkbox to cell D corresponding to the current row
With cb
.LinkedCell = ws.Cells(cell.Row, "D").Address
.Caption = ""
.Placement = xlMoveAndSize
' Retrieve the actual dimensions of the checkbox
cbHeight = .Height
cbWidth = .Width
' Center the checkbox horizontally and vertically
.Left = cell.Left + (cell.Width - cbWidth) / 2
.Top = cell.Top + (cell.Height - cbHeight) / 2
End With
' Set the corresponding cell in column D to TRUE
ws.Cells(cell.Row, "D").Value = True
Next cell
End Sub
The difference is that now the checkboxes are not centered and sometimes they overlap over lines or into the next cell down. Originally, they used to be perfectly centered. Although my rows are uneven in size, I’ve tried on a smaller worksheet with even row sizes, and it still doesn’t work. The weird thing is that it was literally working 2 days ago. Can someone help me figure out why? I’m also open to using Python to read the file and insert the checkboxes if Python can allow me to do that.
user26517739 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.