Jakob Busk Sørensen
Jakob Busk Sørensen

Reputation: 6081

Use strings for object names in VBA

I got a user form with six checkboxes, named chk1, chk2, ..., chk6, which i need to go through and list the marked ones. I would like them to be listed right after each other, such that if there are four marked boxes, the caption of those boxes will be listed in A1:A4 (even if it is not the four first boxes which are marked).

I have tried this code:

Dim i As Integer, n, As Integer
  n = 0
  For i = 1 To 6
    strChkName = "chk" & i
    If strChkName.Value Then
    Cells(1+n, 2) = strChkName.Caption
    n = n + 1
  End If
Next i

This however, does not work. Likely because of the combination of a string and the .Value thing. I cannot seem to find anything regarding this. Is it even possible to do?

Upvotes: 0

Views: 1114

Answers (1)

Jakob Busk Sørensen
Jakob Busk Sørensen

Reputation: 6081

Using comments from Nathan and Scott, I managed to solve the issue using the Controls() function in VBA. Used in my code, it looks like this:

Dim i As Integer, n, As Integer
  n = 0
  For i = 1 To 
    If Controls("chk" & i).Value Then
      Cells(1+n, 2) = Controls("chk" & i).Caption
      n = n + 1
    End If
Next i

Upvotes: 2

Related Questions