VBA Refer to TextBox or Label using a loop

柔情痞子 提交于 2021-01-03 06:16:24

问题


I am trying to replace the following:

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

With:

Dim cCont As Control

For Each cCont In Me.Controls

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

How do I refer to the textbox using the generic 'Control'?


回答1:


You already have your control in 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

If you're confused by the fact you don't get the Text property from IntelliSense, just cast the Control to a more derived type:

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

This will use early binding instead of late binding, and you'll get your code suggestions.



来源:https://stackoverflow.com/questions/6060142/vba-refer-to-textbox-or-label-using-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!