You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将TextBox控件名设为变量并循环操作TextBox1至TextBox20

Fixing Your TextBox Loop Issue

First, let's break down the problems in your current code:

  • You’re using variable Y but never assigning it a value (it defaults to 0), and you should be using your loop variable I instead to target TextBox1 through TextBox20.
  • X is just a string holding the control name, not the actual TextBox control itself. You can’t access a .Value property on a string—you need to reference the real control on your form.

Here’s the corrected code that will clear the text of TextBox1 to TextBox20, depending on your environment:

For VB.NET (WinForms)

Dim I As Integer
For I = 1 To 20
    ' Find the TextBox control by its name
    Dim targetTextBox As TextBox = Me.Controls.Find($"TextBox{I}", True).FirstOrDefault()
    
    ' Only modify the control if it exists (avoids runtime errors)
    If targetTextBox IsNot Nothing Then
        targetTextBox.Text = "" ' TextBoxes use .Text for their content in VB.NET
    End If
Next I

Key Details:

  • Me.Controls.Find($"TextBox{I}", True) searches your form’s controls (including child controls, thanks to the True flag) for the matching TextBox name.
  • .FirstOrDefault() safely returns the control if found, or Nothing if it doesn’t exist—this prevents crashes if a TextBox is missing from your form.

For VBA (Excel/Access)

If you’re working in VBA, the syntax is a bit simpler since TextBoxes use .Value directly:

Dim I As Integer
For I = 1 To 20
    ' Skip errors if the control doesn't exist
    On Error Resume Next
    Me.Controls("TextBox" & I).Value = ""
    On Error GoTo 0
Next I

内容的提问来源于stack exchange,提问作者temesgen-g

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:36:01