0

I'm trying to create a dynamic function that I can pass a range to and it will generate the checkbox in the cells in that range. I have it generating checkboxes but I can't figure out how to change it to use a dynamic range that is passed as a parameter when I call the sub.

How would I change my sub to be able to do this? Here is my code so far...

Public Sub chkPopulateFields(R As Range)
    Dim chk As Variant
    Dim t As Range
    Dim i As Integer

    Application.ScreenUpdating = False

    With Me.Worksheets(1)
        .CheckBoxes.Delete
        For i = 4 To 10
            Set t = .Range(Cells(i, 3), Cells(i, 3))
            Set chk = .CheckBoxes.Add(t.Left, t.Top, t.Width, t.Height)
        Next
    End With

    Application.ScreenUpdating = True
End Sub
0

1 Answer 1

2

I'm trying to create a dynamic function that I can pass a range to and it will generate the checkbox in the cells in that range.

You can use For Each to loop through each cell in a range. Also I added one more paramenter ws As Worksheet so that you can target the relevant worksheet.

Is this what you are trying?

Option Explicit

Sub Sample()
    chkPopulateFields Range("A1:C4"), Sheet1
End Sub

Public Sub chkPopulateFields(R As Range, ws As Worksheet)
    Dim rng As Range
    Dim chk As Object

    With ws
        .CheckBoxes.Delete
        For Each rng In R
            Set chk = .CheckBoxes.Add(rng.Left, rng.Top, rng.Width, rng.Height)
        Next
    End With
End Sub

enter image description here

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

5 Comments

You could have used the Worksheet property of the range object (i.e. R.Worksheet)
True. I could have. But then you would have to fully qualify Range("A1:C4") else it will refer to the activesheet. But honestly R.Worksheet did not even cross my mind :)
It's very convenient as it would have allowed for something like: With rng ` Set chk = .Worksheet.CheckBoxes.Add(.Left, .Top, .Width, .Height)` End With. Anyhow, your answer is very efficient, as always.
Yes it would have been. but unfortunately it also can cause lot of confusion. If you want to use R.Worksheet then fully qualify the range. For example, chkPopulateFields Sheet1.Range("A1:C4") In this case we can get rid of ws As Worksheet and then replace With ws with With R.Worksheet :)
Sorry forgot to mention that the 1With ws` would be replaced by With R (excluding the .Worksheet)

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.