在VBA中使用字符串作为对象名称

时间:2016-01-11 13:02:37

标签: excel vba

我收到了一个包含六个复选框的用户表单,名为chk1chk2,...,chk6,我需要查看并列出标记的复选框。我希望它们能够一个接一个地列出,这样如果有四个标记的框,那些框的标题将列在A1:A4中(即使它不是标记的四个第一个框)。

我试过这段代码:

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

然而,这不起作用。可能是因为字符串和.Value事物的组合。我似乎无法找到任何有关此事的内容。它甚至可以吗?

1 个答案:

答案 0 :(得分:2)

使用Nathan和Scott的评论,我设法使用VBA中的Controls()函数解决了这个问题。在我的代码中使用,它看起来像这样:

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