VBA使用循环引用文本框或标签 [英] VBA Refer to TextBox or Label using a loop

查看:208
本文介绍了VBA使用循环引用文本框或标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to replace the following:

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

如何使用通用的控件"引用文本框?

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

推荐答案

您已经在cCont中拥有控件了.

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

如果您对没有从IntelliSense获得 Text 属性的事实感到困惑,只需将 Control 强制转换为更派生的类型:

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.

这篇关于VBA使用循环引用文本框或标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆