【问题标题】:VBA- Iterating through string values in an array and identifying if they are equal to a specific textVBA-遍历数组中的字符串值并确定它们是否等于特定文本
【发布时间】:2016-10-06 17:40:45
【问题描述】:

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

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

首先,我要查找 ID 所在的行。然后我想遍历不同的列并在它们下找到对应于 ID 的值来填充我的输入表单。

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

如果我直接编写 MRN = Cells(CSN_R, Changing_C),它会使用正确的数据填充输入表单,因为它会选择“MRN”或“Myarray(0)”下的 id 行和列号。但是,如果我使用 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

【问题讨论】:

  • 我刚刚添加了这个,它可以工作,但它需要一堆 if 语句... If myarray(i) = "MRN" Then MRN = Cells(CSN_R, Changing_C) End If If myarray (i) = "ArrivalDate" Then ArrivalDate = Cells(CSN_R, Changing_C) End If

标签: arrays excel vba loops userform


【解决方案1】:

尝试类似:

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

【讨论】:

    【解决方案2】:

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

    看起来您正在尝试将文本分配给用户窗体控件文本框。您应该能够通过用户表单名称引用文本框 - 它叫什么?

    假设它是您可以使用的默认“UserForm1”:

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

    【讨论】:

    • 谢谢!这正是我需要的!
    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2015-07-13
    • 2022-10-04
    相关资源
    最近更新 更多