我需要使用从另一个工作表中查找列并返回单个单元格VBA。 Sheet1中的我的数据是,
P.No. REV Qty
2918 01 50
2918 02 44
2919 01 72
在Sheet2中,它应该通过同时查看Qty
和P.No.
列来返回REV
。请帮助我。
我在下面查找一列的代码。在这里我需要查找两列。
Function SingleCellExtractInward(lookupvalue As String, lookuprange As Range, ColumnNumber As Integer)
Dim i As Double
Dim Result1 As String
Dim Result2 As String
If Result2 = Empty Then
Result2 = "no recent inward"
SingleCellExtractInward = Result2
End If
For i = 1 To lookuprange.Columns(1).Cells.Count
If lookuprange.Cells(i, 1) = lookupvalue Then
Result1 = Result1 & " " & lookuprange.Cells(i, ColumnNumber) & ","
SingleCellExtractInward = Left(Result1, Len(Result1) - 1)
End If
Next i
End Function
答案 0 :(得分:0)
尝试使用此功能:
Function LookupTwoCriteria(strPNo As String, strRev As String)
LookupTwoCriteria = Evaluate("=INDEX(Sheet1!C:C,MATCH(1,(Sheet1!A:A=" & _
strPNo & ")*(Sheet1!B:B=" & strRev & "),0))")
End Function
它使用的数组公式尝试匹配两个条件:strPNo& strRev。在你的单元格中使用它,如:
=LookupTwoCriteria(A1, B1)
如果找不到匹配项,则会显示#VALUE!所以保护它:
=IFERROR(LookupTwoCriteria(A4,B4),0)
如果你愿意的话。
答案 1 :(得分:0)
因此,您只需将您的功能延长一秒lookupvalue
,我们就有lookupValueA
和lookupValueB
:
Function SingleCellExtractInward(lookupValueA As String, lookupValueB As String, _
lookupRange As Range, ColumnNumber As Long)
请注意,我已将Integer
更改为Long
。除非您需要与旧API(see explanation here)进行通信,否则请始终使用Long
代替Integer
。
您需要检查是否符合这两个条件:
If lookupRange.Cells(i, 1).Value = lookupValueA And _
lookupRange.Cells(i, 2).Value = lookupValueB Then
备选方案:如果您希望能够另外只查看一个标准A或B(如果另一个标准为空)则使用:
If (lookupRange.Cells(i, 1).Value = lookupValueA Or lookupValueA = vbNullString) And _
(lookupRange.Cells(i, 2).Value = lookupValueB Or lookupValueB = vbNullString) Then
在这种情况下,您可以保留其中一个lookupValue
一个vbNullString
(与""
相同),它只会查找一个条件(就像您的原始函数一样)。< / EM>
以下只是改进并删除了我推荐的不必要的代码:
i
应为Long
而不是Double
:
Dim i As Long
If Result2 = Empty Then
此时总是如此。所以我们甚至不需要Result2
以下......
Dim Result2 As String
If Result2 = Empty Then
Result2 = "no recent inward"
SingleCellExtractInward = Result2
End If
可以减少到一行...
SingleCellExtractInward = "no recent inward" 'Default return value if nothing matches.
所以我们最终会得到类似的东西:
Option Explicit
Function SingleCellExtractInward(lookupValueA As String, lookupValueB As String, _
lookupRange As Range, ColumnNumber As Long)
Dim i As Long
Dim Result As String
SingleCellExtractInward = "no recent inward"
For i = 1 To lookupRange.Columns(1).Cells.Count
If (lookupRange.Cells(i, 1).Value = lookupValueA Or lookupValueA = vbNullString) And _
(lookupRange.Cells(i, 2).Value = lookupValueB Or lookupValueB = vbNullString) Then
Result = Result & " " & lookupRange.Cells(i, ColumnNumber) & ","
SingleCellExtractInward = Left(Result, Len(Result) - 1)
End If
Next i
End Function