多条件searchfunction不起作用

我有一个函数,它需要2个search值和2列和1个结果列(共5个参数),并返回最后一列的值,如果前两个条件都满足。 但它不起作用并返回VALUE错误。 我无法弄清楚这里有什么问题。

  Function betterSearch(searchValue1 As Variant, searchValue2 As Variant, _ searchColumn1 As Variant, searchColumn2 As Variant, _ resultColumn As Variant) Dim i As Integer For i = 1 To searchColumn1.Rows.Count If searchColumn1.Cells(i, 1).Value = searchValue1 _ And searchColumn2.Cells(i, 2).Value = searchValue2 Then betterSearch = resultColumn.Cells(i, 1) MsgBox ("found") Exit For End If betterSearch = "Not found" Next End Function 

这对我很好 – 更新

  Sub foo44() Dim val As Variant Dim c1 As Range Dim c2 As Range Dim c3 As Range Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") Set c1 = ws.Range("C:C") Set c2 = ws.Range("D:D") Set c3 = ws.Range("E:E") Debug.Print betterSearch(23, 23, c1, c2, c3) End Sub Function betterSearch(searchValue1 As Variant, searchValue2 As Variant, searchColumn1 As Range, searchColumn2 As Range, resultColumn As Range) Dim i As Long Dim c1 As Variant Dim c2 As Variant For i = 1 To searchColumn1.End(xlDown).Row c1 = searchColumn1.Cells(i, 1).Value c2 = searchColumn2.Cells(i, 1).Value ' Debug.Print c1 'Debug.Print c2 If c1 = searchValue1 And c2 = searchValue2 Then betterSearch = resultColumn.Cells(i, 1).Value Exit For End If betterSearch = "Not found" Next End Function 

尝试使用.column属性获取列号。 也可以按照下面的方法获取最后使用的行号:

 Function betterSearch(searchValue1 As Variant, searchValue2 As Variant, _ searchColumn1 As Range, searchColumn2 As Range, _ resultColumn As Range) Dim i As Long For i = 1 To Cells(Rows.Count, searchColumn1.Column).End(xlUp).Row If Cells(i, searchColumn1.Column).Value = searchValue1 _ And Cells(i, searchColumn2.Column).Value = searchValue2 Then betterSearch = Cells(i, resultColumn.Column) MsgBox ("found") Exit For End If betterSearch = "Not found" Next End Function