简体   繁体   English

VBA:确定参数x,y和z为真的行

[英]VBA: Identify row where arguments x,y and z are true

my worksheet looks like: 我的工作表如下所示:

  A        B             c
1 Name     Surname       Weight
2 Pete     Smith         91
3 Pete     Johnson       81

My Userform contains textboxes where one can fill in Name, Surname etc. 我的用户表单包含文本框,您可以在其中填写姓名,姓氏等。

I'm looking for something like: 我正在寻找类似的东西:

RowNumber = (textbox_Name == (A:A) ) & (textbox_Surname == Range(B:B) )

It's not easy to explain but I hope that you get the idea. 解释起来不容易,但我希望您能理解。

I know how to search in one column but does this work also in two? 我知道如何在一列中进行搜索,但是在两列中也可以进行搜索吗?

Use a for loop to go down the sheet and check each cell for your required values, something like: 使用for循环查看工作表并检查每个单元格的所需值,例如:

Dim lastRow as long
Dim sName, surname, weight as string

sName = MyForm.MyControl.text ' etc etc - pick up the other form controls and put them to variables too

lastRow = Range("A1000000").End(xlUp).Row

For x = 2 to lastRow

     If cells(x, 1) = sName And cells(x,2) = surname And cells(x,3) = weight Then
         ' you've found a match
     End if

Next x

This uses the Cells propery of the Range class, the syntax is Cells(row, column) so cell A1 = Cells(1,1), cell C10 = Cells(10, 3) and so on. 这使用Range类的Cells属性,语法为Cells(row,column),因此单元格A1 =单元格(1,1),单元格C10 =单元格(10,3),依此类推。 The for loop increments X at each iteration and thus moves to the next row. for循环在每次迭代时递增X,因此移至下一行。

As @Absinthe posted, a For Loop is perfectly acceptable +1. 正如@Absinthe发布的, For循环是完全可以接受的+1。 If you have lots of rows and find the loop to be slow you might consider using the Match function evaluating on multiple criteria instead. 如果您有很多行并且发现循环很慢,则可以考虑使用Match函数对多个条件求值。

Sub findMatchedRow()
    Dim matchedRow, wks, Criteria1, Criteria2

    Set wks = Worksheets("Sheet1")

    Criteria1 = wks.Cells(2, 7).Address(False, False)
    Criteria2 = wks.Cells(3, 7).Address(False, False)

    matchedRow = wks.Evaluate("MATCH(" & Criteria1 & "&" & Criteria2 & ",A2:A5&B2:B5,0)")

    If Not IsError(matchedRow) Then
        wks.Range("G6") = matchedRow
    Else
        wks.Range("G6") = "Not Found"
    End If
End Sub

在此处输入图片说明


Note that the row number is based on the range and since the header row was not included it shows row 2 instead of actual row 3. You can account for that or just include the header row if it's really on row 1. 请注意,行号是基于范围的,并且由于不包括标题行,因此它显示的是第2行,而不是实际的第3行。您可以考虑这一点,也可以仅包含标题行(如果它确实在第1行上)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM