2

I've added a button to an Excel file which, when clicked, reads a text file and populates a column with lines from a text file. I need to add a checkbox to cells adjacent to certain lines, depending on what the line contains.

Can I create components like checkboxes in code, and if so, how?

Any responses are appreciated.

1

1 Answer 1

1

While the link @Siva provided is certainly valid I just prefer to have an answer on StackOverflow instead of an external link. Hence, here is the solution you might be looking for:

Option Explicit

Public Sub tmpSO()

Dim i As Long
Dim chk As CheckBox

With ThisWorkbook.Worksheets(1)
    .CheckBoxes.Delete
    For i = 1 To .Cells(.Rows.Count, "A").End(xlUp).Row
        If .Cells(i, "A").Value2 = "need checkbox" Then
            Set chk = .CheckBoxes.Add(Left:=.Cells(i, "B").Left, Top:=.Cells(i, "B").Top, Width:=.Cells(i, "B").Width, Height:=10)
            chk.OnAction = "runThisSub"
            chk.Name = "CheckBowInRow" & i
            chk.Caption = "CheckBowInRow" & i
        End If
    Next i
End With

End Sub

Sub runThisSub()

MsgBox "You clicked the checkbox " & Application.Caller _
            & Chr(10) & "in cell " & ThisWorkbook.Worksheets(1).CheckBoxes(Application.Caller).TopLeftCell.Address

End Sub

Copy both subs into a Module into your Excel file and change in the first sub

  1. the sheet where the text is imported to (here it is Worksheet(1)),
  2. the column where the condition can be found (here column A), and also
  3. what the condition is (here the value in column A must be need checkbox).

The code will now look through all cells in column A in sheet Worksheet(1) and check if the value is need checkbox. If so, the code will automatically add a checkbox into column B adjacent to that cell.

If you click on any of the newly created checkboxes then the second sub fires up and will show you in a message box which checkbox in which row has been clicked.

Sign up to request clarification or add additional context in comments.

2 Comments

That is absolutely awesome, thanks so much! May I ask what "Option Explicit" does?
Option Explicit is considered coding best practice. For more information read this: stackoverflow.com/documentation/excel-vba/1107/… and also (if you wish to read Microsoft's thought on this) msdn.microsoft.com/en-us/library/y9341s4f.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.