在用户窗体文本框中循环输入值

时间:2019-11-26 15:11:58

标签: excel vba

我试图编写一个基本循环,该循环在工作表的特定列中查找唯一值。我相信我已经正确声明了我的变量。但是,当我尝试运行我的代码时,它给了我一个溢出错误。我想要的只是让我的宏能够遍历我的数据集,直到找到特定的ID号为止。

以下是我的便于查看的代码:

Sub Macro1()  
    Dim FirstRow As Range
    Dim LastRow As Range
    Dim R As Long

    FirstRow = Worksheets("Petrobras").Range("V2")
    LastRow = Worksheets("Petrobras").Cells(Rows.Count, 22).End(xlUp).Select
    R = TXTOPPNUM_Insert.Value

    For R = FirstRow To LastRow
        Worksheets("Petrobras").Cells(Rows.Count, 22).Find(R, , , Lookat:=xlWhole).Select
    Next R
End Sub

2 个答案:

答案 0 :(得分:0)

这可能会有所帮助:

Sub Macro1()
Dim FirstRow As Long
Dim LastRow As Long
Dim R As Long
Dim tempStore As New collection ' collection is initialized with .Count = 0
Dim uniqueValue As Variant

' is that needed?
'R = TXTOPPNUM_Insert.Value

With Worksheets("Petrobras")

    FirstRow = .Cells(2, 22).row ' set first row
    LastRow = .Cells(Rows.Count, 22).End(xlUp).row ' set last row


    For R = FirstRow To LastRow ' there's an actual loop
        If Application.WorksheetFunction.CountIf(range(.Cells(FirstRow, 22), .Cells(LastRow, 22)), .Cells(R, 22).Value) = 1 Then ' don't think that I have to explain how does the CountIf works
            tempStore.Add .Cells(R, 22).Value ' if the CountIf of value = 1 then adding this value to a collection
        End If
    Next

    If tempStore.Count > 1 Then ' if collection contains more that 1 value - means that there is not one unique value
        MsgBox "There is more then 1 unique value"
    Else
        uniqueValue = tempStore(1) ' if collection contains 1 value - assign the unique value variable
    End If

End With


End Sub

另外,请仔细查看this articlethis one

答案 1 :(得分:0)

为使代码简单,可以使用单行代码,该单行代码可以通过在用户窗体上使用Button_Click来激活;只需将这行代码添加到Button_Click宏即可。在文本框中输入要查找的值,然后单击按钮。

ThisWorkbook.Sheets("Petrobras").Range("V2", Range("V" & Rows.Count).End(xlUp)).Find(What:=Me.TXTOPPNUM_Insert.Value).Select