使用For循环从Excel VBA中的多个文本框中获取值

时间:2014-02-24 14:55:46

标签: string excel vba for-loop

对于Excel中的VBA代码(不是用户表单),我有4个名为TextBox1TextBox4的文本框。

我想使用for循环从这些文本框中获取值。目标是在相应的列中搜索值(在这种情况下为D)。因此,我搜索选定的工作表(以UpdateComboBox中的选定值命名)。为了能够搜索我首先选择与RelatedWeldTextBox_i中显示的焊缝相对应的rownumber。此值与其他输入框不同。

以下代码错误。它创建一个带有for循环的String:例如TextBox1。但它开始在列D中搜索字符串TextBox1,而不是此文本框中显示的值。如果我使用Weld = Textbox1.Value代码有效,但仅适用于Textbox1 ...

Sub RelatedWeldNegative ()

Dim Weld As String
Dim Bmin As Integer
Dim Bmax As Integer 
Dim i As Integer
For i = 1 To 4`

Weld = "Textbox" & i & ".Value"
        For Each Cell In ActiveWorkbook.Sheets(UpdateComboBox.Value).Range("C2:C320")
           If Cell.Text = Weld Then
            SelecRow = Cell.Row
            End If
Next

Next i
Bmax = 6
Bmin = ActiveWorkbook.Sheets(UpdateComboBox.Value).Cell(SelecRow, "D")
'follow up with code
End Sub

提前致谢,

1 个答案:

答案 0 :(得分:3)

以下是如何遍历TextBoxes:

Sub dural()
    For i = 1 To 4
        ActiveSheet.Shapes("TextBox " & i).Select
        MsgBox Selection.Characters.Text
    Next i
End Sub

另一种方式

Sub Sample()
    Dim shp As Shape
    Dim i As Long

    For i = 1 To 4
        Set shp = ActiveSheet.Shapes("TextBox" & i)

        Debug.Print shp.OLEFormat.Object.Object.Text
    Next i
End Sub