2017-01-03 30 views
0

我的工作是這樣的:VBA:確定排在那裏參數x,y和z是真正

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

我的用戶窗體包含我正在尋找的文本框,其中一個可以在填寫姓名,姓氏等

例如:

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

這不容易解釋,但我希望你能明白。

我知道如何在一列中搜索,但這個工作也在兩個?

回答

2

作爲@Absinthe發佈,For Loop是完全可以接受的+1。如果你有很多行並且發現循環很慢,你可以考慮使用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 

enter image description here


注意,行號是基於範圍,因爲沒有被列入標題行就說明,而不是實際的行3.您可佔第2行或者只包含標題行,如果它真的在第1行上。

+0

謝謝波特蘭亞軍! – DataAdventurer

2

使用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 

它使用範圍類的單元格屬性格式,語法單元(ROW,列)所以單元格A1 =單元格(1,1),單元格C10 =單元格(10,3)等等。 for循環在每次迭代時遞增X,並因此移動到下一行。

相關問題