Word vba宏-动态引用表单元素 [英] word vba macro - dynamically reference form elements

查看:127
本文介绍了Word vba宏-动态引用表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已创建的用户窗体,其中包含许多文本框.这些字段中的每一个都被命名为name1,name2,name3等.

I have a userform that I have created that contains a number of TextBoxes. Each of these fields are named name1, name2, name3, etc.

此用户窗体是从用于处理数据的Word宏调用的.根据运行宏的文件中的数据,我希望将数组中的内容显示在每个TextBoxes中.

This userform is called from a Word macro used to process data. Depending on the data in the file the macro is run on, I want content from an array to be displayed in each of those TextBoxes.

我想要做的是动态引用TextBoxes表单,这样我就可以在循环中填充它们,而不必为每个单独的value/TextBox做单独的if语句.

What I want to be able to do is dynamically reference the form TextBoxes so that I can populate them from within a loop, as opposed to having to do a separate if statement for each individual value/TextBox.

因此,例如,不必执行以下操作:

So for example, instead of having to do something like this:

For p = 1 To count
   if p=1 then
       dForm.name1.Text=myVar(p)
   end if
   if p=2 then
       dForm.name2.Text=myVar(p)
   end if
   .
   .
   .
   etc.
Next p

我希望能够实现更简单,更高效的功能,例如:

I want to be able to something much more simple and efficient like:

For p = 1 To count
   tempString = "name" & p
   dForm.tempString.Text = myVar(p)
Next p

不幸的是,我无法弄清楚该怎么做.

Unforunately though, I cannot figure out how to do this.

这可能吗?我一直希望类似于Actionscript的操作可以起作用,但是没有成功(在Actionscript中,我只是做dForm ["name" + p] .Text = myVar [p]).

Is this possible? I had been hoping that something similar to what can be done in Actionscript would work, but it didn't (in Actionscript I would simply just do dForm["name"+p].Text = myVar[p]).

有什么想法/建议吗?我尝试过的所有方法均无济于事,而且我无法在网上找到有关此内容的任何信息.我敢肯定,必须采取一些措施来避免不得不执行大量的if语句("name" TextBoxes仅是我窗体中许多重复的TextBox之一,因此必须执行if语句因为所有这些都将永远消失)...

Any ideas/suggestions? Nothing I've tried has worked, and I haven't been able to find anything online about this. I'm sure there has got to be some work around to avoid having to do an incredible number of if statements (the 'name' TextBoxes' is just one of many repeating TextBoxes that is part of my form, so having to do if statements for all of them would take forever) ...

推荐答案

UserForm1.Controls("name" & p).Value = myVar(p)

或...

Private Sub FillTextBoxes()
    Dim ctl As Control

    For Each ctl In UserForm1.Controls
        If TypeName(ctl) = "TextBox" Then
            If ctl.Name Like "name*" Then
                ctl.Value = myVar(p)
            End If
        End If
    Next
End Sub

这篇关于Word vba宏-动态引用表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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