VBA使用循环引用TextBox或Label

时间:2011-05-19 14:21:12

标签: vba excel-vba excel-2007 excel

我正在尝试替换以下内容:

txt1.Text = ""
txt2.Text = ""
txt3.Text = ""
txt4.text = ""
...continues for quite awhile

使用:

Dim cCont As Control

For Each cCont In Me.Controls

If TypeName(cCont) = "TextBox" Then
'reset textbox value
   ???
End If
Next cCont

如何使用通用“控制”来引用文本框?

1 个答案:

答案 0 :(得分:7)

你已经掌控了cCont。

Dim cCont As Control

For Each cCont In Me.Controls
  If TypeOf cCont Is MSForms.TextBox Then
    cCont.Text = "hi"
    MsgBox cCont.Name
  End If
Next

如果您对未从IntelliSense获取Text属性这一事实感到困惑,只需将Control转换为更加派生的类型:

Dim cCont As Control

For Each cCont In Me.Controls
  If TypeOf cCont Is MSForms.TextBox Then
    Dim cText As MSForms.TextBox

    Set cText = cCont

    cText.Text = "hi"
    MsgBox cText.Name
  End If
Next

这将使用早期绑定而不是后期绑定,您将获得代码建议。