在 Visual Basic 6 中使用数字更改调用 Texbox 的名称

0 vb6 textbox

我正在使用 Visual Basic 6 创建一个包含许多名为 txtNo1、txtNo2、txtNo3 的文本框的表...我想使用“For...Next...”循环为这些文本框分配内容。如何以最简单的方式调用所有这些文本框?

For i = 1 to 100
    txtNo (......) .txt = "ABC"
Next i
Run Code Online (Sandbox Code Playgroud)

Hel*_*een 7

您应该使用(文本框)控件数组,而不是使用唯一的文本框,每个文本框都有唯一的名称:

  • 将第一个文本框放在表单上,​​将其命名为“txtNo”
  • 复制并粘贴到表格上
  • VB 会问你“已经有一个名为‘txtNo’的控件。你想创建一个控件数组吗?”。回答“是”
  • 根据需要多次粘贴为文本框

然后你的代码看起来像

' Control arrays typically start at index 0
For i = 0 to 100
    txtNo(i) .txt = "ABC"
Next i
Run Code Online (Sandbox Code Playgroud)

Jim Mack 的解决方案也适用,为其编写代码:

' Assuming your form is named 'Form1'
For each ctrl in Form1.Controls
   If TypeOf ctrl Is Textbox
      For i = 1 To 100
         If ctrl.Name = "txtNo" & CStr(i) Then
            ctrl.Text = "ABC"
         End If
      End If
   End If
Run Code Online (Sandbox Code Playgroud)

它有点复杂,但因此在使用多种控制类型(在一个循环中)时更灵活。