如何将文本框名称设置为变量,并允许循环更改名称? [英] How to set textbox name as variable and allow to alter the name in loop?

查看:84
本文介绍了如何将文本框名称设置为变量,并允许循环更改名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道标题不清楚.因此,我尝试在内容中进行详细说明.

VB界面中有15个文本框,如下图所示.

There are 15 textbox in the VB interface as picture below .

这是一个用户界面,允许用户输入数据并存储在工作表中.

假设用户填写了全部15个文本框.然后,文本框的第一行将通过并将数据分别存储在Excel单元格A1,B1,C1,D1中.第二行文本框将数据存储在Excel单元格A2,B2,C2,D2 ......

Suppose the user fill all 15 textbox .Then , first row of textbox will pass and store the data in Excel cells A1,B1,C1,D1 correspondingly .The second row of textbox store the data in Excel cells A2,B2,C2,D2 ......

因此,我想使用嵌套循环来解决问题.

 for {for { Cells.(i,j)=textbox1.value 

语句的左侧很好,因为每个Excel单元格都有自己的ID(列和行顺序).

The left side of the statement is fine ,as every Excel cells have their own ID (column and row order ) .

但是,在右侧,每个 TextBox 名称都是由我分配的.我将其命名为textbox1,textbox2,textbox3 ...

However ,for the right hand side ,every TextBox names are assigned by me .I name them as textbox1 ,textbox2 ,textbox3...

为了让他们适应循环,我想在循环中更改其文本框名称.例如,

To let them fit in the loop, i want to change their textbox name during the loop .For example ,

`textbox+i; i++ ;` ' just my thought 

实际上可以做到这一点吗?此外,如果用户在半行中填充数据(第3行有数据,然后提交,第2行为空白).VBA如何继续在有数据的行之后填充数据?

推荐答案

您可以使用以下代码:

For i = 1 To 5 '<-- 5 "rows" of textboxes
    For j = 1 To 3 '<-- 3 "columns" of textboxes for each row
        Cells(i, j) = Me.Controls("TextBox" & (i - 1) * 3 + j) '<-- textboxes are name form "TextBox1" to "TextBox15" rowwise 
    Next j
Next i

根据您的实际行数和列数进行调整.

to be adjusted as per your actual rows and columns number.

关于您的如果...怎么办" 问题,我不清楚您要实现什么目标

as for your "what if..." issue, it's not clear to me what you want to achieve

只想跳过未输入"文本框,那么您可以简单地

should just want to skip "not entered" textboxes, then you could simply go

    For i = 1 To 5 '<-- 5 "rows" of textboxes
        For j = 1 To 3 '<-- 3 "columns" of textboxes for each row
            With Me.Controls("TextBox" & (i - 1) * 3 + j) '<-- textboxes are name form "TextBox1" to "TextBox15" rowwise
                If .Text <> "" Then Cells(i, j) = .Text '<--| skip void textboxes
            End With
        Next j
    Next i

这篇关于如何将文本框名称设置为变量,并允许循环更改名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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