VBA- 遍历数组中的字符串值并确定它们是否等于特定文本

VBA- Iterating through string values in an array and identifying if they are equal to a specific text

我在 excel 中有一个包含很多列的数据集。我正在使用用户窗体条目来填充这些列。但我也希望能够在用户表单中写入一个现有 ID,并使用从电子表格中提取的相应数据自动填充用户表单。列的顺序可能会改变,所以我不想使用偏移函数来执行此操作。

我在我的代码中尝试做的是创建一个包含所有列名称的数组(输入表单中相应的文本框的名称相同)。

首先,我要查找 ID 所在的行。然后我想遍历不同的列并找到它们下面与 ID 对应的值以填充我的条目表单。

问题是我想在我的用户表单中使用 "array(i)" 作为文本框的名称,但它不读取它。例如:

如果我直接写 MRN = Cells(CSN_R, Changing_C),它会用正确的数据填充输入表单,因为它选择了 [=23 下的 id 行号和列号=] 或 "Myarray(0)"。但是如果我使用 myarray(0) =Cells(CSN_R, Changing_C) 它不会......我不知道该怎么做才能让它工作。

    Dim CSN_Find As Range
    Dim CSN_Existing As Range
    Dim CSN_New As Range

    Dim CSN_R As Integer
    Dim Changing_C As Integer

    ' Look for the CSN value

    Worksheets("Input Data").Activate
    Worksheets("Input Data").Rows(1).Find(What:="CSN", LookIn:=xlValues).EntireColumn.Select

    Set CSN_Find = Selection.Find(What:=CSN.Value, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)

    ' If it's found, then populate form

    If (Not CSN_Find Is Nothing) Then

        CSN_Find.Activate
        CSN_R = ActiveCell.Row


        Dim myarray As Variant
        Dim i As Integer
        Dim lastColumn As Integer


        myarray = Array("MRN", "ArrivalDate",...(I have a lot))

        lastColumn = Worksheets("Input Data").Cells(1, columns.Count).End(xlToLeft).Column

        i = 0

        Do Until i = lastColumn + 1

        Changing_C = Worksheets("Input Data").Rows(1).Find(What:=myarray(i), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Column

        myarray(i) = Cells(CSN_R, Changing_C) **** not working

        i = i + 1
        Loop

    ' Else, do nothing:

    Else: If CSN_Find Is Nothing Then Exit Sub

    End If


End Sub

试试这样的东西:

Me.Controls(myarray(i)) = Cells(CSN_R, Changing_C)

当您使用此 myarray(i) = Cells(CSN_R, Changing_C) **** not working 时,您只是在覆盖您的数组值

看起来您想要做的是将文本分配给用户窗体控件文本框。您应该能够通过用户表单名称引用文本框 - 它叫什么?

假设这是默认值 "UserForm1" 您可以使用:

UserForm1.Controls(myarray(i)).Text = Cells(CSN_R, Changing_C)